node.js 如何在 package.json 中使用变量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43705195/
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 18:11:32  来源:igfitidea点击:

How can I use variables in package.json?

node.jsnpm

提问by husayt

There is a feature from maven I miss a lot in package.json. In maven .pom file you can define variables in parent project and use them in child project's pom files.

有一个来自 maven 的特性,我在 package.json 中非常想念。在 maven .pom 文件中,您可以在父项目中定义变量并在子项目的 pom 文件中使用它们。

Is there something like this in npm? We are building modular project and I want to define dependency versions centrally and them to be used in respective package.json files.

npm 中有这样的东西吗?我们正在构建模块化项目,我想集中定义依赖版本,并在相应的 package.json 文件中使用它们。

Thanks

谢谢

回答by Abhay

Any key can be referenced, beginning with $npm_package_and adding an underscore for every level you go down.

可以引用任何键,开始$npm_package_并为您下降的每个级别添加下划线。

Example:

例子:

{ "name": "appname", "version": "0.0.1"}

name can be access like: $npm_package_nameor ${npm_package_name}to delimit within string

名称可以像这样访问:$npm_package_name${npm_package_name}在字符串中分隔

For windows user, name can access like: %npm_package_name%

对于 Windows 用户,名称可以访问如下: %npm_package_name%

回答by Jirik

Define a config object in package.json:

在 package.json 中定义一个配置对象:

{
    "name"   : "myapp",
    "config" : { "port" : "3000" },
    ...
}

And then you can access port value from scrips object with $npm_package_config_port

然后你可以从脚本对象访问端口值 $npm_package_config_port

{
    "name"   : "myapp",
    "config" : { "port" : "3000" },
    "scripts": {
        "start" : "node --harmony app.js $npm_package_config_port"
    },
    ...
}

The source full article is here:

源完整文章在这里:

http://www.marcusoft.net/2015/08/npm-scripting-configs-and-arguments.html#npm-configuration

http://www.marcusoft.net/2015/08/npm-scripting-configs-and-arguments.html#npm-configuration

Here is another example:

这是另一个例子:

http://ianmcnally.me/blog/2016/2/4/variables-in-npm-scripts

http://ianmcnally.me/blog/2016/2/4/variables-in-npm-scripts

回答by Renan Gomes

On Windows, you should use %variable_name%. For example:

在 Windows 上,您应该使用%variable_name%. 例如:

{
   "name": "app_name",
   "version": "1.0.0",
   "custom": {
      "key": "any value"
   }
}

You can get it using %npm_package_name%, %npm_package_version%and %npm_package_custom_key%.

您可以使用%npm_package_name%,%npm_package_version%和来获取它%npm_package_custom_key%