在npm脚本中传递环境变量 [英] Passing environment variables in npm-scripts
问题描述
我有一个package.json,在脚本键中有以下(简化)内容:
I have a package.json with following (simplified) content in the scripts key:
...
scripts: {
"start": "NODE_ENV=${NODE_ENV:=production} node start-app.js",
"poststart": "echo $NODE_ENV"
}
...
从命令行可以运行:
npm start
我的start-app.js脚本,并将process.env.NODE_ENV环境变量设置为production。请参阅此处了解语法说明。
This will run my start-app.js script and set the process.env.NODE_ENV environment variable to "production". See here for syntax explanation.
后启动将自动运行开始之后,此处。
The poststart will automatically run after start as described here.
但是,poststart不会继承NODE_ENV shell环境变量,所以echo命令不会回显任何内容。
However poststart will not "inherit" the NODE_ENV shell environment variable, so the echo command will not echo anything.
我的生成代码有点多复杂,但我正在尝试完成的是将NODE_ENV变量从起点传递到依赖脚本。任何关于如何做的建议/最佳做法?
My producation code is a little more complex, but what I am trying to accomplish is passing down the NODE_ENV variable from the "starting point" to dependent scripts. Any suggestions/best practices on how to do that?
我不想在后台启动时对NODE_ENV进行硬编码,因为我可能想做:
I dont want to hardcode the NODE_ENV in the poststart, because I might want to do:
NODE_ENV=development npm start
而且我想要down the chain,继承同一个环境。
and I want everyting "down the chain" inherit the same environment.
推荐答案
你有几个选择:
- 更好 - npm运行,可以分别为每个命令定义
env
- 而不是
poststart
脚本,您可以像这样连接npm的命令:start:NODE_ENV = $ {NODE_ENV:= production} node start-app.js&& echo $ NODE_ENV
- 在生产中使用流程管理器,如 PM2 。 pm2允许您定义环境特定的json文件,其设置如
NODE_ENV
。在我们公司,我们成功地运行了所有的应用程序在不同的环境与pm2(所有有同样的开始命令)
- better-npm-run,which can define an
env
for each command separately - Instead of a
poststart
script, you can concatenate commands for npm like so:"start": "NODE_ENV=${NODE_ENV:=production} node start-app.js && echo $NODE_ENV"
- Use a process manager in production like pm2. pm2 lets you define environment specific json files with settings such as
NODE_ENV
. At our company, we successfully run all of our apps in different environments with pm2 (all the while having the same start command)
这篇关于在npm脚本中传递环境变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!