typed-env-loader
v1.0.1
Published
A parser of environment variables to typed values
Maintainers
Readme
typed-env-loader
Typed environment variables and values, and intellisense helper.
Mainly for typescript source codes.
Install
You can use typed-env-loader with dotenv, and we recoment it:
npm install dotenv typed-env-loaderRemember to load dotenv in your script:
// for javascript
require('dotenv').config();// for typescript
import 'dotenv/config';Usage
In the simple case, create a configuration file and use loadConfig function to parse your environment variables:
// "config.ts"
import 'dotenv/config';
import { loadConfig } from 'typed-env-loader';
export const Config = loadConfig({
port: { name:'PORT', type:'number', defaultValue: 80 },
// ...
});
// -----------------
// "main.ts"
import { Config } from './config';
console.log(`Port: ${Config.port}`);
// After that you have access to "Config.port" and other configurations defined.
// And ( typeof Config.port === 'number' ) is "true", the value was converted to javascript 'number' type.You can split your configurations in parts with the defineConfig function.
This functions does nothing but will let intellisense aware of the typings.
// "config.ts"
import 'dotenv/config';
import { loadConfig, defineConfig } from 'typed-env-loader';
// "defineConfig" receives the same object than "loadConfig"
export const ConfigPresetDatabase = defineConfig({
databaseUrl: { name: 'DATABASE_URL', type: 'string', defaultValue: '' },
databaseUsername: { name: 'DATABASE_USERNAME', type: 'string', defaultValue: '' },
databasePassword: { name: 'DATABASE_PASSWORD', type: 'string', defaultValue: '' },
});
export const ConfigPresetServer = defineConfig({
serverPort: { name: 'PORT', type: 'number', defaultValue: 5000 },
serverRouteContext: { name: 'ROUTE_CONTEXT', type: 'string', defaultValue: '' },
serverCookiesSecure: { name: 'SERVER_COOKIES_SECURE', type: 'boolean', defaultValue: false },
});
export const ConfigPresetSMTP = defineConfig({
smtpHost: { name: 'SMTP_HOST', type: 'string', defaultValue: '' },
smtpPort: { name: 'SMTP_PORT', type: 'number', defaultValue: 587 },
smtpUser: { name: 'SMTP_USER', type: 'string', defaultValue: '' },
smtpPass: { name: 'SMTP_PASS', type: 'string', defaultValue: '' },
});
export const Config = loadConfig({
...ConfigPresetDatabase,
...ConfigPresetServer,
...ConfigPresetSMTP,
// and define others configs
another: { name:'ANOTHER', type:'string', defaultValue: 'default string' },
// ...
});Parameters and configurations
loadConfig(config: T, envObjArr?: Record<string, any>[] | Record<string, any> | null, mergeConfig?: any, extraConfig?: Partial<EnvExtraConfig> | null): R
Loads configuration from environment variables, or theenvObjArrinformed.config: the configuration definition object. Need to follow the typeEnvDefinition, that is an object where the keys will be the key in the loaded configuration (the returned value of this function) and the values as configuration definitions of typeEnvConfig.
Possible configurations ofEnvConfigare:name: defaults to the key name
The name of the configuration on the environment or theenvObjArrparam. If not set, the will be the same as the key of this line:
loadConfig({ PORT: { type:'number' }, // "name" will be "PORT" })type: defaults toauto
Type of the value to parse. Possible values are inEnvConfigTypeFieldtype:'auto' , 'boolean' , 'number' , 'string', 'auto[]' , 'boolean[]' , 'number[]' , 'string[]'
Values with[]in the end will be loaded asarrays.
Theautotype will try to guess the type, but will not find arrays automaticaly.separator: defaults to/\s*(?:(?<!\\)[,;])+\s*/g
Separator to use onsplit()function when loading arrays. Can be a string or aRegExp.
The defaultRegExpwill use,and;characters, and use backslash\to escape the separator characters.
loadConfig({ TEXTS: { type:'string[]' }, // with "TEXTS" env == "Hello world\, friends! , Lets develop!;Lovely Devs" // "TEXTS" will load "['Hello world, friends!', 'Lets develop!', 'Lovely Devs']" })If you want to define your separator, consider using the lookbehind of this default value to have the same escape capabilities.
defaultValue: defaults to none
The default value that will be loaded if the environment doenst have a variable defined.choices: defaults to none
A list of acceptable values for this configuration.
If the type is an array then all values parsed need to be one of these items.
// loads fine loadConfig({ ENV: { type:'string', choices:['dev','stage','prod'] }, // with "ENV" env == "prod" LOG_LEVEL: { type:'string', choices:['info','warn','error'] }, // with "LOG_LEVEL" env == "info" PLUGINS: { type:'string[]', choices:['feat01','extra02','another03'] }, // with "PLUGINS" env == "feat01, another03" }) // --- // an error will be thrown in that cases loadConfig({ ENV: { type:'string', choices:['dev','stage','prod'] }, // with "ENV" env == "uat" LOG_LEVEL: { type:'string', choices:['info','warn','error'] }, // with "LOG_LEVEL" env == "debug" PLUGINS: { type:'string[]', choices:['feat01','extra02','another03'] }, // with "PLUGINS" env == "feat01, super04" })readonly: defaults totrue
If the load configuration need to define the property to readonly.
const Config = loadConfig({ ENV: { type:'string', readonly: true }, // with "ENV" env == "prod" }) Config.ENV = 'dev'; // will throw an Error // --- const Config02 = loadConfig({ ENV: { type:'string', readonly: false }, // with "ENV" env == "prod" }) Config02.ENV = 'dev'; // after that "Config02.ENV" have the value "dev"envObjArr: an object to load configurations from. Defaults toprocess.env. An array of objects can be set to load from them.mergeConfig: the object to where the loaded configurations will be put in. This is the same object returned by the function. If not set then a new object will be created and returned.extraConfig: configurations for general behavior ofloadConfigfunction. Acceptable configurations are inEnvExtraConfigtype:const Config = loadConfig({ ENV: { type:'string' }, // with "ENV" env == "prod" }, null, null, new EnvExtraConfig({ readonlyDefault: false })) Config.ENV = 'dev'; // after that "Config02.ENV" have the value "dev"exitOnError: defaults toprocess.exit
A functions to be called when some error occurs during load, like a parse error, an env not defined, achoiceserror.
Define tonullto not exit on errors.exitErrorCode: defaults to1
Error code to use in the call of the functions defined inexitOnError.throwOnError: defaults tofalse
Instead of callingexitOnError, when this configurations istruethen anErrorwill be thrown, so that it can be catch by your code.loggerError: defaults toconsole.error
Logger to call when errors occurs. Need to have similar interface ofconsole.error.
Set tonullto not log errors.readonlyDefault: defaults totrue
Default behavior ofreadonlyitem configuration.
