Utility for parsing environment variables and bootstrapping configuration objects.
@nkp/config
exports both CommonJS and ES modules.
npm install @nkp/config
yarn add @nkp/config
pnpm add @nkp/config
import { parse, boolean, string, integer, key, oneOf } from '@nkp/config';
/**
* the parse function correctly sets the type of `config`
* {
* DEBUG: false;
* MAIL: string | undefined;
* HOST: string;
* PORT: number;
* env: 'development' | 'testing' | 'production';
* }
*/
const config = parse({
// coerces DEBUG is a boolean defaulting to false if not provided
DEBUG: boolean().default(false),
// coerces MAIL_HOST to string, or leaves undefined if it doesn't exist
MAIL_HOST: string().optional(),
// coerces process.env.HOST to string
HOST: string() ,
// coerces process.env.PORT to string
// if not provided, defaults to 3000
PORT: integer().default(3000),
// ensures procese.env.NODE_ENV is one of the given values
env: key('NODE_ENV')
.oneOf(['development', 'testing', 'production',] as const),
}, process.env);
Instead of parsing an object, a single key can be parsed.
import { key, string } from '@nkp/config';
// by key - required
const email1: string = key('EMAIL')
.string()
.parse(process.env);
// by key - optional
const email2: string | undefined = key('EMAIL')
.string()
.optional()
.parse(process.env);
// by value - with default
const email3: string = string()
.default('example@example.com')
.parse(process.env['EMAIL']);
Default values can be provided.
import { key, integer } from '@nkp/config';
const port = key('PORT').integer().default(3000).parse(process.env);
If no default value is provided and the key is not found, an error will be thrown.
import { key, string } from '@nkp/config';
const vars = {};
const value = key('MISSING_VALUE').string().parse(vars);
// throws TypeError "MISSING_VALUE is not defined"
To a release a new version:
- Update the version number in package.json
- Push the new version to the
master
branch on GitHub - Create a
new release
on GitHub for the latest version
This will trigger a GitHub action that tests and publishes the npm package.