classenv
A perfect typescript class environment variables library.
- Strongly-typed declarative class containing your environment data
- Supports both static and instance properties
- Type-casting using TypeScript metadata reflection
- Auto UPPER_SNAKE_CASE conversion
- Converts environment values "FALSE", "false", "0" to false for boolean types
- Throws runtime error if variable doesn't exist
- Default values support
- Makes decorated properties read-only in runtime
Description
Let's pretend we have very simple
.env
IS_SOMETHING_ENABLED=1
How can we describe it using classenv
environment.ts
import { Env } from 'classenv';
export class Environment {
@Env()
static isSomethingEnabled: number;
@Env()
isSomethingEnabled: number;
@Env()
static withDefault: string = 'yeah its me'
@Env('IS_SOMETHING_ENABLED')
static isEnabledStr: string;
@Env('IS_SOMETHING_ENABLED')
static isEnabledNmbr: number;
@Env('IS_SOMETHING_ENABLED')
static isEnabledBln: boolean;
}
@Env
property data type should be scalar (string, number or boolean).
main.ts
import {Environment} from './environment.ts'
console.log(typeof Environment.isEnabledStr, Environment.isEnabledStr)
console.log(typeof Environment.isEnabledNmbr, Environment.isEnabledNmbr)
console.log(typeof Environment.isEnabledBln, Environment.isEnabledBln)
console.log(typeof Environment.isSomethingEnabled, Environment.isSomethingEnabled)
Environment.isEnabledBln = false;
const env = new Environment();
console.log(env.isSomethingEnabled)
Dependencies
reflect-metadata
npm i reflect-metadata
And then import it somewhere close to your entry point (index.ts
/main.ts
/etc...).
Should be imported before any of your environment classes.
import 'reflect-metadata';
tsconfig.json
These settings should be enabled
"emitDecoratorMetadata": true,
"experimentalDecorators": true,