Published at
Updated at
Reading time
2min
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 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/*"
  }
}

Looking closely, there's a duplicated definition of ./src/* 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.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, some package.json values will be available via process.env, too.

If you have the following package.json...

{
  "name": "my-name",
  "version": "1.0.0",
  "config": {
    "foo": "bar"
  },
  "scripts": {
    "start": "node index.js"
  }
}

... run the npm script npm start and access package.json values in your script via process.env.

// index.js

console.log(process.env.npm_package_version); // '1.0.0'
console.log(process.env.npm_package_name); // 'my-name'
console.log(process.env.npm_package_config_foo); // 'bar'

Read more about this feature in the npm documentation.

That's all cool stuff!

Was this TIL post helpful?
Yes? Cool! You might want to check out Web Weekly for more quick learnings. The last edition went out 9 days ago.
Stefan standing in the park in front of a green background

About Stefan Judis

Frontend nerd with over ten years of experience, freelance dev, "Today I Learned" blogger, conference speaker, and Open Source maintainer.

Related Topics

Related Articles