English | 中文文档
dotenv-multi
Use dotenv to parse and load variables from multiple env files to process.env, and distinguish between different modes.
// with npm
npm install dotenv-multi
// with yarn
yarn add dotenv-multi
const dotenvMulti = require('dotenv-multi');
dotenvMulti.loadEnv({ dir: 'path/to/envFileDir', mode: 'myMode' });
loadEnv(options: LoadOptions): Result
loadEnv will parse and merge the following files into process.env
in the dir
folder.
- .env
- .env.local
- .env.[mode]
- .env.[mode].local
Note:
- Priority of the above files from low to high
- The file will be skipped if the file does not exist
- Will not overwrite the original value in
process.env
- The method used to merge the variables in the file is "Object.assign".
Assume that there are some env files in the env/
folder
// .env
foo=foooooo
URL=api.default.com
endpoint=path/to/endpoint
// .env.dev
URL=api.dev.com
// .env.local
URL=api.dev-local.com
e1=some-local-var
//.env.stg
URL=api.stg.com
//.env.prd
bar=barrrrr
URL=api.prd.com
//.env.prd.local
URL=api.prd.com
enpoint=/another/path/to/endpoint
proxy=/another
Suppose we distinguish the modes through process.env.API
const dotenvMulti = require('dotenv-multi');
dotenvMulti.loadEnv({ dir: './env', mode: process.env.API });
Start the script in different ways as follows
# load .env、.env.local、.env.dev、.env.dev.local
$ cross-env API=dev npm run some-script
# load .env、.env.local、.env.stg、.env.stg.local
$ cross-env API=stg npm run some-script
# load .env、.env.local、.env.prd、.env.prd.local
$ cross-env API=prd npm run some-script
Then we can get the corresponding environment variables in the project
Key | Type | Default | Required | Description |
---|---|---|---|---|
dir | string | process.cwd() |
N | Directory path where env files are stored |
mode | string | process.env.NODE_ENV | N | current mode |
interface ParseSuccess {
parsed: { [props: string]: string };
error: null;
}
interface ParseError {
error: Error;
parsed: null;
}
👤 render
- Website: http://render.ink
- Github: @zjcrender
Give a ⭐️ if this project helped you!