This content originally appeared on Stefan Judis Web Development and was authored by Stefan Judis
I came across this tweet by Jess Telford. He shared that you can reference values that are defined in your package.json
inside of your npm/yarn scripts.
Let's have a look at an example.
{
"name": "my-package",
"scripts": {
"lint": "eslint ./src/*",
"test": "jest ./src/*"
}
}
What you see there is the duplicated definition of ./src/*
in two different scripts. For the case of these two scripts, the duplication might not be a big deal, but in larger projects, it can be way harder. I worked on projects that defined very complex scripts which were hard to read and maintain. In this scenario, you want to avoid any repetition.
npm and yarn provide a nice feature to get around this problem. Inside of the scripts
section of your package.json
you can reference all the values that are defined. For example, the name
property is available at npm_package_name
. This behavior allows you to reuse values. ?
{
"name": "my-package",
"config": {
"src": "./src/*"
},
"scripts": {
"lint": "eslint $npm_package_config_src",
"test": "jest $npm_package_config_src"
}
}
I think this is very kind of npm/yarn and good to know.
Edited:
As Michael Kühnel pointed out – when you run Node.js files via npm/yarn scripts the package.json
values will be available via process.env
, too.
If you have the following package.json
...
{
"foo": "bar"
"scripts": {
"start": "node index.js"
}
}
... you can run npm start
in you terminal. And the index.js
file then has access to the package.json
values in process.env.
// index.js
console.log(process.env.npm_package_foo); // 'bar'
Cool stuff!
Reply to Stefan
This content originally appeared on Stefan Judis Web Development and was authored by Stefan Judis
Stefan Judis | Sciencx (2019-03-27T23:00:00+00:00) Package.json values are accessible in npm/yarn scripts (#tilPost). Retrieved from https://www.scien.cx/2019/03/27/package-json-values-are-accessible-in-npm-yarn-scripts-tilpost/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.