简体   繁体   中英

Cannot access NPM environment variables

In my package.json I have set a config variable called "foo" to "bar", and I am calling that variable with an NPM script.

"config": {
    "foo": "bar"
    },
"scripts": {
    "test": "echo $npm_package_config_foo"
    }

Running npm run test should output bar , but it doesn't.

I suspect that I have a general issue accessing environmental variables. As an example, I can use uglifyjs from NPM scripts but not from the command line.

Running printenv from the command line doesn't show up any of the NPM variables that one would expect.

Setup: OSX 10.11.6, NPM 2.15.11, Node 6.2.0.

What you are trying is wrong: node environment variables are only accessible using process global variable in a node process, not system-wide. So to achieve what you want you have to do is make following changes.

package.json

"config": {
    "foo": "bar"
    },
"scripts": {
    "test": "node ./app.js"
    }

app.js

console.log(process.env.npm_package_config_foo);

you can find more information here

My solution:

  1. Set foo using npm config set foo bar

  2. Removed the config object from my package.json.

  3. Change $npm_package_config_foo to $npm_config_foo in the NPM scripts properties

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