在package.json中访问环境变量

时间:2021-01-01 23:05:51

To access an environment variable in npm scripts you would do something like this in your package.json:

要在npm脚本中访问环境变量,您可以在package.json中执行以下操作:

"scripts": {
    "preinstall": "echo ${npm_package_name}"
}

The problem is that works only in Unix, not Windows, where you have to use %npm_package_name%.

问题是只能在Unix中使用,而不能在Windows中使用%npm_package_name%。

Is there a way to do this OS independent? It will be good if npm could do such a variable expansion, before invoking the command.

有没有办法让这个OS独立?如果npm在调用命令之前可以进行这样的变量扩展,那将是很好的。

2 个解决方案

#1


23  

To make it cross-platform, use cross-var:

要使其跨平台,请使用cross-var:

"scripts": {
    "preinstall": "cross-var echo ${npm_package_name}"
}

#2


2  

There's no known way to do this that's OS independent.

没有已知的方法来执行此操作系统独立操作。

A good workaround is to execute the command within a node script:

一个好的解决方法是在节点脚本中执行命令:

First, change the preinstall command to execute a node script:

首先,更改preinstall命令以执行节点脚本:

"scripts": {
    "preinstall": "node nameEcho.js"
}

Then you define the command in the nameEcho.js file:

然后在nameEcho.js文件中定义命令:

// require the package.json file
var pjson = require('./package.json');

// echo the package's name
console.log(pjson.name);

#1


23  

To make it cross-platform, use cross-var:

要使其跨平台,请使用cross-var:

"scripts": {
    "preinstall": "cross-var echo ${npm_package_name}"
}

#2


2  

There's no known way to do this that's OS independent.

没有已知的方法来执行此操作系统独立操作。

A good workaround is to execute the command within a node script:

一个好的解决方法是在节点脚本中执行命令:

First, change the preinstall command to execute a node script:

首先,更改preinstall命令以执行节点脚本:

"scripts": {
    "preinstall": "node nameEcho.js"
}

Then you define the command in the nameEcho.js file:

然后在nameEcho.js文件中定义命令:

// require the package.json file
var pjson = require('./package.json');

// echo the package's name
console.log(pjson.name);