如何从包中设置一些环境变量。Json使用NPM启动像命令?
以下是我目前在package.json中的内容:
{
...
"scripts": {
"help": "tagove help",
"start": "tagove start"
}
...
}
我想在启动脚本中设置环境变量(如NODE_ENV),同时仍然能够用一个命令启动应用程序,npm start。
如何从包中设置一些环境变量。Json使用NPM启动像命令?
以下是我目前在package.json中的内容:
{
...
"scripts": {
"help": "tagove help",
"start": "tagove start"
}
...
}
我想在启动脚本中设置环境变量(如NODE_ENV),同时仍然能够用一个命令启动应用程序,npm start。
当前回答
{
...
"scripts": {
"start": "ENV NODE_ENV=production someapp --options"
}
...
}
其他回答
在script命令中设置环境变量:
...
"scripts": {
"start": "node app.js",
"test": "NODE_ENV=test mocha --reporter spec"
},
...
然后使用process.env。NODE_ENV在你的应用中。
注意:这只适用于Mac和Linux。对于Windows,请参阅注释。
在Windows上尝试替换YOURENV:
{
...
"scripts": {
"help": "set NODE_ENV=YOURENV && tagove help",
"start": "set NODE_ENV=YOURENV && tagove start"
}
...
}
虽然没有直接回答这个问题,但我想在其他答案的基础上分享一个想法。从我得到的信息来看,每一个都提供了一定程度的复杂性来实现跨平台独立性。
在我的场景中,最初我只想设置一个变量来控制是否使用JWT身份验证来保护服务器(出于开发目的)
在阅读了答案后,我决定简单地创建2个不同的文件,分别打开和关闭身份验证。
"scripts": {
"dev": "nodemon --debug index_auth.js",
"devna": "nodemon --debug index_no_auth.js",
}
这些文件只是调用原始index.js文件的包装器(我将其重命名为appbootstrap .js):
//index_no_auth.js authentication turned off
const bootstrapper = require('./appbootstrapper');
bootstrapper(false);
//index_auth.js authentication turned on
const bootstrapper = require('./appbootstrapper');
bootstrapper(true);
class AppBootStrapper {
init(useauth) {
//real initialization
}
}
也许这能帮助到其他人
这将在Windows控制台工作:
"scripts": {
"setAndStart": "set TMP=test&& node index.js",
"otherScriptCmd": "echo %TMP%"
}
运行aaa
输出: 测验
详情请看这个答案。
{
...
"scripts": {
"start": "ENV NODE_ENV=production someapp --options"
}
...
}