JSPM

  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 43
  • Score
    100M100P100Q73498F
  • License MIT

Simple solution to define your environments

Package Exports

  • cfg-tools
  • cfg-tools/dist/index.js

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (cfg-tools) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

cfg-utils

A tiny, type-safe configuration helper for environment variables based on dotenv with developer-friendly validation.


✨ Features

  • ⚡ Zero-boilerplate configuration management
  • 🛡️ Full type safety without maintaining manual types
  • 🧠 Auto-infers config structure from your factory
  • ✅ Required variables with validation
  • ⚠️ Optional variables with default values and warnings
  • 📦 Dotenv support included

📦 Installation

npm install cfg-utils

dotenv is a required peer dependency.


🚀 Quick Start

// config.ts
import { initCfg } from 'cfg-utils';

const cfg = initCfg((ct) => ({
    nodeEnv: ct.recommendToBeDefined('string', 'NODE_ENV', 'development'),
    app: {
        port: ct.mustBeDefined('number', 'PORT'),
        debug: ct.recommendToBeDefined('boolean', 'DEBUG', false),
    },
}));

export const AppEnv = cfg.env;
// main.ts
import { AppEnv } from './config';

console.log(AppEnv.app.port); // number
console.log(AppEnv.app.debug); // boolean
console.log(AppEnv.nodeEnv); // string

Features

You can also use your own aliases for "recommendToBeDefined" and "mustBeDefined" methods.

import { initCfg, bindCfgTools } from 'cfg-utils';

const cfg = initCfg(initFn);
const { mustBeDefined: must, recommendToBeDefined: should } = bindCfgTools(cfg.tools);

const a = must("string", "A_STRING_VAR");
const b = should("number", "A_NUMBER_VAR", 0);

🛠️ API

initCfg(fn, opts?)

Initializes your configuration. Takes:

  • a factory function: (tools) => ({ ...your config })
  • optional dotenv config

Returns an object: { env } where env is your parsed and validated config.


Tools available inside the factory:

mustBeDefined(type, key): string | number | boolean

Fails the application if the variable is missing or invalid.

recommendToBeDefined(type, key, defaultValue): string | number | boolean

Uses the default if the variable is missing or invalid. Emits a warning.

Supported types:

  • 'string'
  • 'number'
  • 'boolean'

📁 Example .env

PORT=3000
NODE_ENV=production
DEBUG=true

🧪 Type Inference

No need to define a separate type — config type is inferred automatically:

type AppEnv = typeof cfg.env;

🧷 License

MIT