使用 .env 文件进行变量赋值

Viv*_*shi 6 environment-variables node.js express

我有一个 .env 文件,看起来像:

NODE_ENV = local
PORT = 4220
BASE_URL = "http://198.**.**.**:4220/"

PROFILE_UPLOAD = http://198.**.**.**:4220/uploads/profile/
POST_UPLOAD = http://198.**.**.**:4220/uploads/discussion/
COMPANY_UPLOAD = http://198.**.**.**:4220/uploads/company/
ITEM_UPLOAD  = http://198.**.**.**/uploads/item/
GROUP_UPLOAD  = http://198.**.**.**/uploads/group/
Run Code Online (Sandbox Code Playgroud)

我想做这样的事情:

NODE_ENV = local
IP = 198.**.**.**
PORT = 5000
BASE_URL = http://$IP:$PORT/

PROFILE_UPLOAD = $BASE_URL/uploads/profile/
POST_UPLOAD = $BASE_URL/uploads/discussion/
COMPANY_UPLOAD = $BASE_URL/uploads/company/
ITEM_UPLOAD  = $BASE_URL/uploads/item/
GROUP_UPLOAD  = $BASE_URL/uploads/group/
Run Code Online (Sandbox Code Playgroud)

的预期结果BASE_URLhttp://198.**.**.**:4220/

我尝试了很多语法但没有得到计算值

尝试过的语法:"${IP}", ${IP}, $IP

我使用dotenv package 来访问 env 变量。

Viv*_*shi 10

dotenv-expand是@maxbeatty 回答的解决方案,以下是要遵循的步骤

脚步 :

首先安装:

npm install dotenv --save
npm install dotenv-expand --save
Run Code Online (Sandbox Code Playgroud)

然后更改 .env 文件,如:

NODE_ENV = local
PORT = 4220
IP = 192.***.**.**
BASE_URL = http://${IP}:${PORT}/

PROFILE_UPLOAD = ${BASE_URL}/uploads/profile/
POST_UPLOAD = ${BASE_URL}/uploads/discussion/
COMPANY_UPLOAD = ${BASE_URL}/uploads/company/
ITEM_UPLOAD  = ${BASE_URL}/uploads/item/
GROUP_UPLOAD  = ${BASE_URL}/uploads/group/
Run Code Online (Sandbox Code Playgroud)

最后一步 :

var dotenv = require('dotenv');
var dotenvExpand = require('dotenv-expand');

var myEnv = dotenv.config();
dotenvExpand(myEnv);

process.env.PROFILE_UPLOAD; // to access the .env variable
Run Code Online (Sandbox Code Playgroud)

或(更短的方式)

require('dotenv-expand')(require('dotenv').config()); // in just single line
process.env.PROFILE_UPLOAD; // to access the .env variable
Run Code Online (Sandbox Code Playgroud)


max*_*tty 5

dotenv-expand是在 dotenv 之上构建的,旨在解决这个特定问题