Package.json values are accessible in npm/yarn scripts

2 min read

This post is part of my Today I learned series in which I share all my learnings regarding web development.

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!

Related Topics

See null comment.