Contains the functions of the following libraries
- Multiple
.envfile support - Command Line support
- Assign a mode mode
File Priority:
.localfile > not unassigned local.modefile > not unassigned mode
If the mode is ‘dev’, then the import order is:
.env.dev.local.env.dev.env.local.env
# the local file has higher priority
# in .env file
HOST=127.0.0.1
PORT=3000
# in .env.local file
PORT=3001
# out
{"HOST": "127.0.0.1", "PORT": "3001"}
# the assigned mode file has higher priority
# in .env file
PORT=3000
# in .env.prod file
PORT=80
# mode=prod
# out
{"PORT": "80"}
💡If you have used vite, it works the same way.
npm i dotenv-multi-x
# or
yarn add dotenv-multi-x
import dotenv from 'dotenv-multi-x'
dotenv.init()
console.log(process.env)
or auto initial
// notice, keep it in the top of file.
import dotenv from 'dotenv-multi-x/lib/init'
console.log(process.env)
$ dotenv node ./example/cli.test.js
$ dotenv --mode=dev node ./example/cli.test.js
OR
$ node -r dotenv-multi-x/lib/init.js ./example/cli.test.js
$ node -r dotenv-multi-x/lib/init.js ./example/cli.test.js --mode=dev
- init
- parse
- getConfig
init will get mode from process.env or process.argv, read the .env* files, parse the content, handle the inheritance, and reture an object.
dotenv.init()
Parse the content and return an Object with the parsed keys and values.
dotenv.parse(Buffer.from('PROT=3001'))
Accept a mode and read .env* files, and handle the inheritance. return finally result.
# Windows Powershell
$env:mode="dev"
node .\example\index.mjs
# Mac
mode=dev node ./example/index.mjs
# or
node .\example\index.mjs --mode=dev
Add .env.local* in your .gitignore file.
When you run your code in multiple environments, you may need some different environments variable. But dotenv didn’t support multiple .env files.
If you don’t use docker or other CI/CD environment variable to instead of .env file, or don’t use shell script to replace .env file, the multiple files is the easiest way to make it work.
For example, your server launched on port 3000, but you want to run on 3001 in local device, the .env file will be shared on repos which used git, so you need a .env.local file, this file has higher-priority then .env and it can doesn’t share with git.
You can create mutiple .env* files, and use them in different environments as easier as possible.

Leave a Reply