Quick Start
Pick the package that matches how you build your app. They all read the same
.env files and share the same options, so you can mix and match.
The most popular way to use .env files in Angular. It supports the modern
application/esbuild builder as well as Webpack, and requires no configuration.
1. Add it to your Angular project
ng add @ngx-env/builder2. Define NG_APP_* variables in a .env file
NG_APP_API_URL=https://api.example.comNG_APP_VERSION=$npm_package_versionOnly variables prefixed with NG_APP_ are exposed to your app.
3. Use them in your code
@Component({ selector: 'app-footer', template: `{{ version }} — {{ apiUrl }}`,})export class FooterComponent { apiUrl = import.meta.env.NG_APP_API_URL; // recommended version = process.env.NG_APP_VERSION; // also supported}…or directly in index.html:
<title>My App %NG_APP_VERSION%</title>4. Run Angular as usual
npm startRun any command with your .env variables loaded into process.env — no
code changes required.
1. Install
npm install -D @dotenv-run/cli2. Create a .env file
API_HOST=api-sandbox.comAPI_INSTANCE=$USER-instanceAPI_BASE=https://$API_INSTANCE.$API_HOST/Notice how API_BASE expands the other variables.
3. Run your command
npx dotenv-run -- printenv✔ /sample/.envAPI_HOST=api-sandbox.comAPI_INSTANCE=chihab-instanceAPI_BASE=https://chihab-instance.api-sandbox.com/Override any value from the command line, and layer environment-specific files
with NODE_ENV:
NODE_ENV=prod npx dotenv-run -- npm start✔ /sample/.env.prod # loaded because NODE_ENV=prod✔ /sample/.envThe engine behind every integration. Use @dotenv-run/core to load .env files
from your own scripts or to build a custom integration.
1. Install
npm install @dotenv-run/core2. Load your variables
import { env } from '@dotenv-run/core';
env({ root: '../..', // walk up to the workspace root (monorepo) prefix: '^API_', // only inject API_* variables verbose: true, // print which .env files were loaded});
console.log(process.env.API_USERS);Given these files:
.env # API_USERS=$API_BASE/v1/users.env.dev # API_BASE=https://localhost:3000.env.prod # API_BASE=https://dotenv-run.appthen:
NODE_ENV=dev node index.jshttps://localhost:3000/v1/users
NODE_ENV=prod node index.jshttps://dotenv-run.app/v1/usersUsing a bundler instead?
dotenv-run ships plugins that share the exact same behaviour as the CLI —
.env.* files, variable expansion and monorepo cascading all work the same way.