我使用在 dev 中工作的 dotenv 读取 .env 的代码,但是在使用 Babel 进行反编译之后,来自 process.env 的值是未定义的。我创建了一个示例程序来说明下面的问题。
如果我在 projectRoot 并运行
npm run start-w
然后
console.log(process.env.VAR1)
打印值 'var1Val'
但是,如果我这样做
npm run build
cd dist
node index.js
VAR1 的值是“未定义”。
index.js
import 'dotenv/config'
console.log('VAR1', process.env.VAR1)
.env
VAR1=var1val
VAR2=var2val
VAR3=var3val
.babelrc
{
"presets": ["@babel/preset-env"],
"plugins": [
"@babel/plugin-transform-runtime",
]
}
包.json
{
"name": "dotenv.node-babel",
"version": "1.0.0",
"description": "",
"main": "index.js",
"dependencies": {
"@babel/runtime": "^7.4.3",
"dotenv": "^7.0.0"
},
"devDependencies": {
"@babel/cli": "^7.4.3",
"@babel/core": "^7.4.3",
"@babel/node": "^7.2.2",
"@babel/plugin-transform-runtime": "^7.4.3",
"@babel/preset-env": "^7.4.3",
"@types/dotenv": "^6.1.1",
"nodemon": "^1.18.11",
"rimraf": "^2.6.3"
},
"scripts": {
"clean-dist": "rimraf dist",
"build": "npm run-script clean-dist && babel . -d dist --ignore node_modules",
"start": "babel-node index.js",
"start-w": "NODE_ENV=devLocal nodemon --exec babel-node index.js"
},
"author": "",
"license": "ISC"
}