简体   繁体   English

如何在 npm 脚本中使用环境变量的值?

[英]How do I use value of env variable in npm script?

I want to set and use an env variable in npm script.我想在 npm 脚本中设置和使用环境变量。 The reason for doing so is that our npm package will get built in CI pipeline, and CI machines have predefined env variables for artifacts/coverage/test paths.这样做的原因是我们的 npm package 将构建在 CI 管道中,并且 CI 机器为工件/覆盖/测试路径预定义了 env 变量。 In developer's local machines, those paths don't exist so need a default value.在开发人员的本地计算机中,这些路径不存在,因此需要一个默认值。

"scripts": {
    "test": "COVERAGE_PATH=${COVERAGE_PATH:-./build/coverage} istanbul cover --dir ${COVERAGE_PATH} --include-all-sources tape -- tests/*.js",
    "build": "ARTIFACTS_PATH=${ARTIFACTS_PATH:-./build/} browserify -r ./index.js > ${ARTIFACTS_PATH}/bundle.js",
}

On local machine ($COVERAGE_PATH is not defined here so fallback value will be used), when I run npm run test , the coverage gets generated and put in a directory named --include-all-sources .在本地机器上($COVERAGE_PATH 未在此处定义,因此将使用回退值),当我运行npm run test时,会生成覆盖率并将其放入名为--include-all-sources的目录中。 Essentially when npm runs the script command, it ignores the value of ${COVERAGE_PATH} .本质上,当 npm 运行脚本命令时,它会忽略${COVERAGE_PATH}的值。 I tried changing it to `echo $COVERAGE_PATH` in the npm script, but still same result.我尝试在 npm 脚本中将其更改为`echo $COVERAGE_PATH` ”,但结果仍然相同。

I even tried defining the variables in my shell beforehand before running the npm run script command, but any ${VAR} in the script still does not get replaced.在运行 npm 运行脚本命令之前,我什至尝试在我的 shell 中预先定义变量,但脚本中的任何${VAR}仍然没有被替换。 How do I get the value of env variables to be correctly replaced in npm scripts.如何在 npm 脚本中正确替换环境变量的值。

EDIT:编辑:
To make it clear, I want to know how to get correct variable value replaced in following cases:为了清楚起见,我想知道如何在以下情况下替换正确的变量值:

  1. VAR=build node ${VAR}/app.js
  2. SOMEVAR=build node ${SOMEVAR}/app.js

AFAIK it is not possible to use bash-like defaults like ${VAR:foo} , only simple expansions work ${VAR} .据我所知,不可能使用类似 bash 的默认值,如${VAR:foo} ,只有简单的扩展才有效${VAR}

When a variable is not defined, it will be expanded to empty string.当未定义变量时,它将被扩展为空字符串。 This reduces the usability of variables considerably, especially in places where you need an implicit value that is not empty.这大大降低了变量的可用性,尤其是在需要非空隐式值的地方。

Environmental variables in NodeJS are read like: NodeJS中的环境变量的读取方式如下:

var value = process.env.VARIABLE;

process is internal variable, and VARIABLE is your actual one that you are looking for. process是内部变量,而VARIABLE是您要查找的实际VARIABLE

You can then pass those variables to node like (when starting the server): 然后,您可以将这些变量传递给节点,例如(启动服务器时):

VARIABLE=test node app.js

Tweak the last one depending on how you run your tests and stuff, but basically environmental variables are read like I showed in the first example. 根据您运行测试和内容的方式来调整最后一个,但是基本上像我在第一个示例中所示那样读取环境变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM