@codemonster-ru/env
v1.1.0
Published
Environment variables loader from .env file for Node.js
Downloads
10
Maintainers
Readme
@codemonster-ru/env
Environment variables loader from .env file for Node.js.
Installation
npm install @codemonster-ru/envor
yarn add @codemonster-ru/env✨ Opportunities
- Loads the
.envfile and writes variables toprocess.env. - Works without errors if
.envis missing (defaults are used). - Supports
\nand\r\n(Windows/Linux). - Automatically removes quotes from values.
- Three usage styles:
env()function (for simplicity).loadEnv()+env()(for loading control).Envclass (for working with multiple files).
Usage
Option A - Simple (recommended for most)
import { env } from '@codemonster-ru/env';
// Takes the PORT value from .env or returns 3000
const port = env('PORT', '3000');Option B - Explicit loading
import { loadEnv, env } from '@codemonster-ru/env';
// Load .env.production
loadEnv('.env.production');
const dbHost = env('DB_HOST', 'localhost');
const dbPort = env('DB_PORT', '5432');Option C - Multiple Files (via Class)
import { Env } from '@codemonster-ru/env';
const mainEnv = new Env('.env');
const testEnv = new Env('.env.test');
console.log(mainEnv.get('PORT')); // from .env
console.log(testEnv.get('PORT')); // from .env.test📑 Example .env
PORT=4000
DB_HOST="localhost"
DB_USER=admin
DB_PASS=secret🔹 Using with TypeScript
To work type-safely, you can define an environment variable interface:
interface AppEnv {
PORT: string;
DB_HOST: string;
DB_USER: string;
DB_PASS: string;
}
// Convenient wrapper for env()
function getEnv<K extends keyof AppEnv>(key: K, defaultValue?: string): AppEnv[K] {
return env(key, defaultValue) as AppEnv[K];
}
const port = getEnv('PORT', '3000'); // type string
const dbHost = getEnv('DB_HOST', 'localhost');
const dbUser = getEnv('DB_USER');Option with the Env class
import { Env } from '@codemonster-ru/env';
const env = new Env();
function getEnv<K extends keyof AppEnv>(key: K, defaultValue?: string): AppEnv[K] {
return env.get(key, defaultValue) as AppEnv[K];
}
const dbPass = getEnv('DB_PASS'); // type stringThis way, if you make a typo in the key (getEnv("DB_HOTS")), TypeScript will immediately indicate the error.
Scripts
npm test-- run tests
