Artboard 16light, inspiration, solution, idea, innovation,Google Sheets iconSwift icon
Published at
Updated at
Reading time
1min
This post is part of my Today I learned series in which I share all my web development learnings.

I came across this tweet by Jess Telford. He shared that you can reference values defined in your package.json inside your npm/yarn script definitions.

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 two scripts, this duplication might not be a big deal, but repeated values can be way harder to discover and change in larger projects.

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. You can reference all the package.json values in the scripts section of your package.json.

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.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 your terminal. The index.js file then has access to the package.json values via process.env.

// index.js

console.log(process.env.npm_package_foo); // 'bar'

That's all cool stuff!

Related Topics

Related Articles