npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

env-smart

v2.3.1

Published

Zero-dependency library for loading .env files. Supports default values and type definitions.

Downloads

16,111

Readme

env-smart

Zero-dependency library for using .env files with types and default values

ci coverage npm license

env-smart is a lightweight, zero-dependency library for loading configuration from environmental variables and .env files in JavaScript or TypeScript. It is designed to solve two common issues with environmental variables:

  • Variable types
  • Default values

In both situations, logic specific to the configuration (type casting, default checking) ends up seeping into the application logic. If any of these values are re-used in different parts of the app this can even lead to duplication.

Instead, env-smart enables declaring default values and types for all environmental variables in additional configuration files. It loads the contents of the .env file if present, but defaults and type checking are applied to the process' env if not.

Installation

npm install env-smart

Usage

Calling .load() populates process.env with the contents of a .env file in the root directory of your project, as well as the process' environmental variables.

// Modules
import env from 'env-smart';
env.load();

// CommonJS
require('env-smart').load();

console.log(process.env.PORT);

Using a .env file to store environmental variables makes managing different configurations between deployments much easier. Example file:

PORT=8080
VERBOSE=TRUE
API_KEY=xyz

Strictly Typed Configuration

If you're using TypeScript, the config function makes parsing strictly typed configurations simple:

import envSmart from 'env-smart';

// Define config type
export type Configuration = {
  host: string;
  port: number;
  verbose: boolean;
};

// Transform the dictionary into a configuration type
export const config = envSmart.config<Configuration>((env) => {
  // `env` is now populated from the .env file, process env, and defaults
  return {
    host: env.HOST,
    port: env.PORT,
    verbose: env.VERBOSE
  };
});

// `config` is now strictly typed
console.log(`Host: ${config.host} port: ${config.port} verbose: ${config.verbose} `);

Types and Defaults

In addition to the main .env file, env-smart also checks for two additional optional configuration files: .env.defaults and .env.types.

Default values are set in the .env.defaults file:

PORT=80
VERBOSE=FALSE

If an environmental variable is otherwise empty empty, it's value from .env.defaults will be used.

Types are set in the .env.types file:

PORT=number
VERBOSE=boolean

Supported types are: string, number, boolean, object and array.

Alternatively, variable types may be declared inline in the .env.defaults file:

PORT=number=80
VERBOSE=boolean=FALSE

Once defaults and types are set, loading is a breeze:

require('env-smart').load();

console.log(`${process.env.PORT}: ${typeof process.env.PORT}`);
// 80: number

Process environmental variables take precedence over the contents of a .env file, and type checking is still applied.

export PORT=8080 && node index.js
require('env-smart').load();
console.log(`${process.env.PORT}: ${typeof process.env.PORT}`);
// 8080: number

Both .env.defaults and .env.types should not contain any secrets, and should be committed to version control systems. Be careful to never commit the .env file.

Options

The load() function supports a few optional parameters:

require('env-smart').load({
  directory: __dirname, // manually specify the directory to load .env files from
  encoding: 'utf8', // manually specify the encoding of the .env files
  lowercase: true, // make all keys lower case.
  // uppercase: true, // make all keys upper case
  verbose: true, // output debug information to the console
  process: false, // if set to false, don't parse the process env, only dotfiles
  inlineTypes: false, // don't allow inline type declarations in .env or .env.defaults, e.g. PORT=number=8080

  envFilename: '.env', //  manually specify .env file name
  envDefaultsFilename: '.env.defaults', // manually specify .env.defaults file name
  envTypesFilename: '.env.types' // manually specify .env.types file name
});

// The 'PORT' value has been re-named 'port' by including the `lowercase` option
console.log(`${process.env.port}: ${typeof process.env.port}`);

Include replace: false option to return the parsed values without replacing the contents of process.env:

const settings = require('env-smart').load({ replace: false, lowercase: true });

console.log(settings.port);

License

MIT © Jesse T Youngblood