Environment
Node.js Environment
Categories:
Environment variable
Install Packages
npm install dotenv --save
yarn add dotenv
Create a .env file
APP_ENV=dev
PORT=5566
Get the env variable
Normal import
// server.js
require('dotenv').config()
console.log(process.env);
console.log(process.env.APP_ENV);
console.log(process.env.PORT);
ES6 import
// server.js
import * as dotenv from 'dotenv' // see https://github.com/motdotla/dotenv#how-do-i-use-dotenv-with-import
dotenv.config();
console.log(process.env);
console.log(process.env.APP_ENV);
console.log(process.env.PORT);
Test to get the environment variable
node server.js
Pass environment variable via CLI command
APP_ENV=production PORT=7788 node server.js
// server.js
require('dotenv').config()
console.log(process.env);
console.log(process.env.APP_ENV); // production
console.log(process.env.PORT); // 7788
Environment variable priority
If you use the .env file and pass the environment variable via CLI command at the same time, then the dotenv will use the CIL environment variable first.
- CLI environemnt variable
- .env file environemnt variable
Reference
- How is cross-env different from dotenv ? · Issue #56 · kentcdodds/cross-env · GitHub
- 设置环境变量cross-env vs dotenv - 掘金