我有一个.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/
我想做这样的事情:
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/
BASE_URL
的预期结果为http://198.**.**.**:4220/
我尝试了很多语法但没有获得计算值
尝试语法:"${IP}"
,${IP}
,$IP
我使用 dotenv 包来访问env变量。
答案 0 :(得分:2)
dotenv-expand是@maxbeatty回答的解决方案,以下是要遵循的步骤
步骤:
首次安装:
npm install dotenv --save
npm install dotenv-expand --save
然后更改.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/
最后一步:
var dotenv = require('dotenv');
var dotenvExpand = require('dotenv-expand');
var myEnv = dotenv.config();
dotenvExpand(myEnv);
process.env.PROFILE_UPLOAD; // to access the .env variable
OR(缩短方式)
require('dotenv-expand')(require('dotenv').config()); // in just single line
process.env.PROFILE_UPLOAD; // to access the .env variable
答案 1 :(得分:1)
dotenv-expand建立在dotenv之上,以解决这个特定问题
答案 2 :(得分:0)
不幸的是dotenv
无法合并变量。检查this issue以查看更多内容并找到适合您项目的解决方案。
答案 3 :(得分:0)
如前所述,您无法在.env文件中分配变量。您可以将* _UPLOAD文件移动到config.js file
并将其检入.gitignore,然后就可以了
//config.js
const BASE_URL = `http://${process.env.IP}:${process.env.PORT}/`
module.exports = {
PROFILE_UPLOAD: BASE_URL+"uploads/profile/",
POST_UPLOAD: BASE_URL+"uploads/discussion/",
....
}