Skip to content

Core · @dotenv-run/core

@dotenv-run/core is the engine behind every dotenv-run integration. Use it to load .env files from your own scripts, or to build a custom integration for a tool that isn’t covered yet. Every plugin (CLI, Vite, Webpack, Rollup, esbuild, Angular) is a thin wrapper around this package.

Install

Terminal window
npm add @dotenv-run/core

Usage

index.js
import { env } from '@dotenv-run/core';
env({
root: '../..', // walk up to the workspace root (monorepo)
prefix: '^API_', // only inject API_* variables
files: ['.env'],
verbose: true, // print which .env files were loaded
});
console.log(process.env.API_USERS);

Given the following files:

Terminal window
.env # API_USERS=$API_BASE/v1/users
.env.dev # API_BASE=https://localhost:3000
.env.prod # API_BASE=https://dotenv-run.app

then:

Terminal window
NODE_ENV=dev node index.js
https://localhost:3000/v1/users
NODE_ENV=prod node index.js
https://dotenv-run.app/v1/users

env() returns the resolved variables so you can inject them yourself (for example into a bundler’s define):

const { full, filtered } = env({ prefix: '^NG_APP_' });
// full -> every resolved variable, keyed as process.env.KEY
// filtered -> only the variables matching `prefix`

Options

OptionTypeDescription
rootstringPath to the workspace root to search up to (monorepo).
cwdstringDirectory to start searching for .env files from.
filesstring[]Base .env file names to load (default ['.env']).
environmentstringEnvironment name, e.g. prod → also loads .env.prod.
prefixstring | RegExpOnly inject variables matching this prefix / pattern.
verbosebooleanPrint the .env files that were loaded.
unsecurebooleanAlso print variable values in verbose output.
nodeEnvbooleanRead the current environment from NODE_ENV.

environment defaults to NODE_ENV, so NODE_ENV=prod loads .env.prod on top of .env. See loading priorities.

License

MIT © Chihab Otmani