node.js 操作系统独立访问 package.json 中的变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36260436/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
OS independent access to variables in package.json
提问by Adrian Ber
To access a 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.
有没有办法独立于这个操作系统?如果 npm 可以在调用命令之前进行这样的变量扩展,那就太好了。
回答by Mark Woon
回答by gnerkus
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 preinstallcommand to execute a node script:
首先,更改preinstall命令以执行节点脚本:
"scripts": {
"preinstall": "node nameEcho.js"
}
Then you define the command in the nameEcho.jsfile:
然后在nameEcho.js文件中定义命令:
// require the package.json file
var pjson = require('./package.json');
// echo the package's name
console.log(pjson.name);

