问题描述
我正在尝试使用package.json设置和检索节点应用程序process.env vars,因此通过研究此问题,我找到了一个通过"config"部分设置/检索process.env的示例,因此我添加了新的配置部分,如下所示:
I am trying to set and retrieve node app process.env vars using package.json, so by researching the issue, I've found an example to set / retrieve process.env through the 'config' section, so I added a new config section as shown below :
"config" : { "var1" : "test", "var2" : "test2", "var3" : "test3" },
但是我无法使用例如来自server.js的任何上述变量:
But I couldn't access any of the above vars from server.js using for example:
console.log(process.env.npm_package_config_var1);
所以我想知道如何使用package.json设置/检索process.env var?谢谢
So I was wondering how I can set / retrieve process.env var using package.json? Thanks
*我正在使用npm 4.4.1,节点7.4.0,并且我使用(npm run dev)运行应用程序
*I am using npm 4.4.1, node 7.4.0 and I run the app using (npm run dev)
推荐答案
您不能只在package.json中设置环境变量.
You cannot just set environment variables in package.json.
您可以使用以下命令在脚本部分中进行设置:
You can set them in your script sections using:
"scripts": {
"start": "ENV_VAR=abc node app.js",
},
或:
"scripts": {
"start": "cross-env ENV_VAR=abc node app.js",
},
使用cross-env模块.参见:
using the cross-env module. See:
环境变量是程序在运行时获取的东西,而不是存储在配置中的东西-除非您使用诸如dotenv之类的东西,否则请参见:
Environment variables are something that your programs get at runtime, not something stored in a config - unless you use something like dotenv, see:
但这使用的是.env
文件,而不是package.json.
but this is using the .env
file, not package.json.
这篇关于在package.json中设置process.env var的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!