psergiocf
psergiocf

Reputation: 1617

Use variables in package.json

It's possible to access variables inside a package.json file with $npm_package_[key]. 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_name:$npm_package_version"
}

I need to reuse the value of the key myvariable in multiple scripts, but unexpectedly, the printed value is $npm_package_name:$npm_package_version instead of the expected core:1.0.0.

I'm currently using:

Upvotes: 7

Views: 7428

Answers (2)

Dixon Gunasekara
Dixon Gunasekara

Reputation: 111

If you're using 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

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

Upvotes: 1

Ayman Arif
Ayman Arif

Reputation: 1679

I am highlighting 3 ways to do this. Each way is an increment to the prior way.

1. First approach

package.json:

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

Start npm:

var1=10 npm start

2. Second approach

First approach would fail if user fails to add var1 while running npm. Better approach is to use a default value

package.json:

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

Start npm:

  • var1=20 npm start : Using passed value
  • npm start : Uses defined default value

Let's now look at the final approach

3. Third approach

If you want to access variables in multipe scripts, you need npm-run-all dependency.

Install dependency:

npm i -D npm-run-all

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:

var1=10 npm start

Upvotes: 5

Related Questions