在 npm-scripts 中传递环境变量 [英] Passing environment variables in npm-scripts

查看:60
本文介绍了在 npm-scripts 中传递环境变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 package.json,在 scripts 键中有以下(简化的)内容:

<代码>...脚本:{"start": "NODE_ENV=${NODE_ENV:=production} 节点 start-app.js",poststart":回声 $NODE_ENV"}...

我可以从命令行运行:

npm 开始

这将运行我的 start-app.js 脚本并将 process.env.NODE_ENV 环境变量设置为生产".请参阅此处了解语法说明.

poststart 将在启动后自动运行,如 here">here 所述.p>

但是 poststart 不会继承" NODE_ENV shell 环境变量,因此 echo 命令不会回显任何内容.

我的生产代码稍微复杂一些,但我想要完成的是将 NODE_ENV 变量从起点"传递到依赖脚本.关于如何做到这一点的任何建议/最佳实践?

我不想在 poststart 中硬编码 NODE_ENV,因为我可能想做:

NODE_ENV=development npm start

我希望每个下游"都继承相同的环境.

解决方案

你有几个选择:

  • better-npm-run,可以定义一个env 分别为每个命令
  • 除了 poststart 脚本之外,您还可以像这样为 npm 连接命令:"start": "NODE_ENV=${NODE_ENV:=production} node start-app.js && echo $NODE_ENV"
  • 在生产中使用流程管理器,例如 pm2.pm2 允许您使用 NODE_ENV 等设置定义特定于环境的 json 文件.在我们公司,我们使用 pm2 在不同的环境中成功运行了我们所有的应用程序(同时具有相同的启动命令)

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"
}
...

From the command line I can run:

npm start

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.

However poststart will not "inherit" the NODE_ENV shell environment variable, so the echo command will not echo anything.

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?

I dont want to hardcode the NODE_ENV in the poststart, because I might want to do:

NODE_ENV=development npm start

and I want everyting "down the chain" inherit the same environment.

解决方案

You have a few options:

  • 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-scripts 中传递环境变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆