简体   繁体   English

无法访问NPM环境变量

[英]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. 在我的package.json中,我将名为“ foo”的配置变量设置为“ bar”,并且正在使用NPM脚本调用该变量。

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

Running npm run test should output bar , but it doesn't. 运行npm run test应该输出bar ,但是不输出。

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. 例如,我可以从NPM脚本中使用uglifyjs,但不能从命令行中使用。

Running printenv from the command line doesn't show up any of the NPM variables that one would expect. 从命令行运行printenv不会显示任何人们期望的NPM变量。

Setup: OSX 10.11.6, NPM 2.15.11, Node 6.2.0. 设置:OSX 10.11.6,NPM 2.15.11,节点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 的package.json

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

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 设置foo使用npm config set foo bar

  2. Removed the config object from my package.json. 从我的package.json中删除了配置对象。

  3. Change $npm_package_config_foo to $npm_config_foo in the NPM scripts properties 在NPM scripts属性$npm_package_config_foo $npm_config_foo更改$npm_package_config_foo $npm_config_foo

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

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