Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

  • nodejs version v10.16.3
  • macOS Catalina v10.15.3
like image 902
psergiocf Avatar asked Oct 16 '22 04:10

psergiocf


1 Answers

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
like image 174
Ayman Arif Avatar answered Oct 18 '22 23:10

Ayman Arif