surenv
TypeScript icon, indicating that this package has built-in type declarations

1.1.0 • Public • Published

Surenv (Sure + Env)

Surenv

Handy environment variables reader with some extra features

Why

Surenv allows you to extract environment variables and provide type definitions for them.

Using it you may have a "source of truth" environment variables provider for your app, with good DX by providing autocompletion based on variables requested.

It can prevent application from running if some required environment variables are missing.

It also support prefixes/namespaces by autocomputing aliases based on provided configuration.

Install

npm i surenv

Use

env-source-of-truth.ts

import Surenv from 'surenv';

// Surenv constructur argument is optional, see below
const { required, optional } = new Surenv({ prefix: 'MY_APP' });

export default {
  // Will try to resolve or fail VAR_NAME or PREFIX_VAR_NAME
  ...required(
    'NODE_ENV',
    'SERVER_ENV',
    'OTHER_VERY_IMPORTANT_VARIABLE',
  ),
  // Will try to resolve VAR_NAME or PREFIX_VAR_NAME
  ...optional(
    'NOT_IMPORTANT_VARIABLE',
    'THIS_ONE_ALSO_NOT_IMPORTANT'
  ),
}

in your editor

DX Snapshot

Hint 💡

For better optional variables checks set strictNullChecks in your tsconfig.json to true.

Configure

Surenv constructor optinally accepts configuration object.

type SurenvConfig = {
    /**
   * It should ignore errors
   * [Default]: process.env - in nodejs environment
   *            {}          - in browser environment
   */
  env?: NodeJS.ProcessEnv | Record<string, string>
  /**
   * Prefix to append to requested variable
   * [Default]: undefined
   */
  prefix?: string;
  /**
   * Should it silintly pass all the errors
   * [Default]: false
   */
  isSilent?: boolean;
  /**
   * Are empty string values allowed?
   * [Default]: false
   */
  allowEmpty?: boolean;
  /**
   * Can it "console.error" when variable is missing?
   * [Default]: true
   */
  shouldWarn?: boolean;
  /**
   * Can it throw an error when variable is missing?
   * [Default]: false
   */
  shouldThrow?: boolean;
  /**
   * Can it "process.exit(1)" when variable is missing?
   * [Default]: true
   */
  shouldExit?: boolean;
};

Package Sidebar

Install

npm i surenv

Weekly Downloads

0

Version

1.1.0

License

MIT

Unpacked Size

9.82 kB

Total Files

14

Last publish

Collaborators

  • b12k