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:
v10.16.3
v10.15.3
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 valuenpm start
: Uses defined default valueLet'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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With