Package.json values are accessible in npm/yarn scripts
- Published at
- Updated at
- Reading time
- 2min
I came across this tweet by Jess Telford. He shared you can reference values defined in your package
inside your npm/yarn script definitions.
Let's have a look at an example.
{
"name": "my-package",
"scripts": {
"lint": "eslint ./src/*",
"test": "jest ./src/*"
}
}
Looking closely, there's a duplicated definition of
in the two scripts. It might not be a big deal, but repeated values can be way harder to discover and change in larger projects.
I worked on projects coming with very complex and hard to maintain scripts. In these cases, fewer repitition leads to fewer headaches.
npm and yarn provide a feature to get around this problem. You can reference all the package
values in the scripts
section of your package
.
For example, the name
property is available at npm_package_name
so that you can reuse defined values. 🎉
{
"name": "my-package",
"config": {
"src": "./src/*"
},
"scripts": {
"lint": "eslint $npm_package_config_src",
"test": "jest $npm_package_config_src"
}
}
Michael Kühnel pointed out that when you run Node.js files via npm/yarn scripts, some package
values will be available via process
, too.
If you have the following package
...
{
"name": "my-name",
"version": "1.0.0",
"config": {
"foo": "bar"
},
"scripts": {
"start": "node index.js"
}
}
... run the npm script npm start
and access package
values in your script via process
.
// index.js
console.log(process.env.npm_package_version); // '1.0.0'
console.log(process.env.npm_package_name); // 'my-name'
console.log(process.env.npm_package_config_foo); // 'bar'
Read more about this feature in the npm documentation.
That's all cool stuff!
Join 5.5k readers and learn something new every week with Web Weekly.