简体   繁体   English

在 package.json 中使用变量

[英]Use variables in package.json

It's possible to access variables inside a package.json file with $npm_package_[key] .可以使用$npm_package_[key]访问 package.json 文件中的变量。 I need to make something like this, but had no success:我需要做这样的事情,但没有成功:

{
  "name": "core"
  "version": "1.0.0"
  "scripts": {
    "first": "echo $npm_package_myvariable"
    "second": "echo $npm_package_myvariable"
  }
  "myvariable": "$npm_package_core:$npm_package_version"
}

I need to reuse the value of the key myvariable in multiple scripts, but unexpectedly, the printed value is $npm_package_core:$npm_package_version instead of the expected core:1.0.0 .我需要在多个脚本中重用myvariable键的值,但出乎意料的是,打印的值是$npm_package_core:$npm_package_version而不是预期的core:1.0.0

I'm currently using:我目前正在使用:

  • nodejs version v10.16.3 nodejs 版本v10.16.3
  • macOS Catalina v10.15.3 macOS Catalina v10.15.3

I am highlighting 3 ways to do this.我强调了 3 种方法来做到这一点。 Each way is an increment to the prior way.每一种方式都是前一种方式的增量。

1. First approach 1. 第一种方法

package.json : package.json :

{
  "name": "core"
  "version": "1.0.0"
  "scripts": {
    "start": "echo $var1"
  }
}

Start npm : Start npm

var1=10 npm start

2. Second approach 2. 第二种方法

First approach would fail if user fails to add var1 while running npm.如果用户在运行 npm 时未能添加 var1,第一种方法将失败。 Better approach is to use a default value更好的方法是使用默认值

package.json : package.json :

{
  "name": "core"
  "version": "1.0.0"
  "scripts": {
    "start": "echo ${var1:10}"
  }
}

Start npm:启动 npm:

  • var1=20 npm start : Using passed value var1=20 npm start :使用传递的值
  • npm start : Uses defined default value npm start :使用定义的默认值

Let's now look at the final approach现在让我们看看最后的方法

3. Third approach 3. 第三种方法

If you want to access variables in multipe scripts, you need npm-run-all dependency.如果要访问多脚本中的变量,则需要npm-run-all依赖项。

Install dependency:安装依赖:

npm i -D npm-run-all

package.json : package.json :

{
  "name": "core"
  "version": "1.0.0"
  "scripts": {
    "start": "npm-run-all multi:*",
    "multi:first": "echo ${var1:-10}"
    "multi:second": "echo ${var1:-10}"
  }
}

Start npm:启动 npm:

var1=10 npm start

If you're using Linux如果您使用的是 Linux

{
  "name": "core",
   "version": "1.0.0",
   "scripts": {
     "first": "echo $npm_package_name:$npm_package_version"
      "second": "echo $npm_package_name:$npm_package_version"
    }
}

If you're using Windows如果您使用的是 Windows

{
  "name": "core",
   "version": "1.0.0",
   "scripts": {
     "first": "echo %npm_package_name%:%npm_package_version%"
      "second": "echo %npm_package_name%:%npm_package_version%"
    }
}

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

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