DEV Community

Stefan Judis
Stefan Judis

Posted on • Originally published at stefanjudis.com on

TIL: Package.json values are accessible in npm/yarn scripts

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/*"
  }
}
Enter fullscreen mode Exit fullscreen mode

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"
  }
}
Enter fullscreen mode Exit fullscreen mode

I think this very kind of npm/yarn and good to know.

I released a package to read package.json values from the environment, too!

I continued reading the Twitter thread about this discovery and Jordon Harband asked the questions if it would make sense to have the same behavior inside of Node.js files. I took a quick night coding session to make that possible with npm-package-to-env.

Assuming you have a package.json as follows:

{
  "name": "my-package",
  "config": {
    "foo": "bar"
  }
}
Enter fullscreen mode Exit fullscreen mode

You can then require npm-package-to-env, run config and access the values via process.env.

require('npm-package-to-env').config();

console.log(process.env.npm_package_name); // 'my-package'
console.log(process.env.npm_package_config_foo); // 'bar'
Enter fullscreen mode Exit fullscreen mode

The config command reads out your package.json and makes the data available via process.env. Maybe you think that's useful, too. :)

Top comments (0)