What is dotenv-expand?
The dotenv-expand npm package is an extension for dotenv. It allows you to have more complex .env files by enabling variable expansion within your environment variables. This means you can reference other environment variables within your .env file, which dotenv by itself does not support.
What are dotenv-expand's main functionalities?
Variable Expansion
This feature allows you to reference other variables in your .env file. For example, if you have a BASE_URL variable, you can use it to construct the API_URL variable.
require('dotenv').config();
require('dotenv-expand')(process.env);
// .env file
// BASE_URL=https://myapi.com
// API_URL=${BASE_URL}/v1
Nested Variable Expansion
This feature allows for nested variable expansion where you can use multiple environment variables to construct a new one.
require('dotenv').config();
require('dotenv-expand')(process.env);
// .env file
// URL=https://myapi.com
// VERSION=v1
// API_URL=${URL}/${VERSION}
Other packages similar to dotenv-expand
env-cmd
env-cmd is a simple node program for executing commands using an environment from an env file. It is similar to dotenv-expand in that it helps manage environment variables, but it does not support variable expansion.
cross-env
cross-env allows you to run scripts that set and use environment variables across platforms. It is similar to dotenv-expand in the sense that it helps with environment variables, but it does not support .env file variable expansion.
envfile
envfile is a package to parse and stringify the envfile format. It is similar to dotenv-expand in that it works with .env files, but it does not support variable expansion within the .env file itself.
dotenv-expand
Dotenv-expand adds variable expansion on top of
dotenv. If you find yourself needing to
expand environment variables already existing on your machine, then
dotenv-expand is your tool.
Install
npm install dotenv --save
npm install dotenv-expand --save
Usage
As early as possible in your application, require dotenv and dotenv-expand, and
wrap dotenv-expand around dotenv.
var dotenv = require('dotenv')
var dotenvExpand = require('dotenv-expand')
var myEnv = dotenv.config()
dotenvExpand(myEnv)
See test/.env for examples of variable expansion in your .env
file.