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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 20:05:09  来源:igfitidea点击:

OS independent access to variables in package.json

node.jsnpmenvironment-variablespackage.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

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

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

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

回答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);