Package.json values are accessible in npm/yarn scripts
- Published at
- Updated at
- Reading time
- 1min
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, the package
values will be available via process
, too.
If you have the following package
...
{
"foo": "bar"
"scripts": {
"start": "node index.js"
}
}
... you can run npm start
in your terminal. The index
file then has access to the package
values via process
.
// index.js
console.log(process.env.npm_package_foo); // 'bar'
That's all cool stuff!
Yes? Cool! You might want to check out Web Weekly for more quick learnings. The last edition went out 7 days ago.