简体   繁体   中英

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

I want to set and use an env variable in npm script. 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. 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 . Essentially when npm runs the script command, it ignores the value of ${COVERAGE_PATH} . I tried changing it to `echo $COVERAGE_PATH` in the npm script, but still same result.

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. How do I get the value of env variables to be correctly replaced in npm scripts.

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

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:

var value = process.env.VARIABLE;

process is internal variable, and VARIABLE is your actual one that you are looking for.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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