Published at
Updated at
Reading time
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, 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!

Was this TIL post helpful?
Yes? Cool! You might want to check out Web Weekly for more quick learnings. The last edition went out 7 days ago.

Related Topics

Related Articles

About the author

Stefan standing in the park in front of a green background

Frontend nerd with over ten years of experience, "Today I Learned" blogger, conference speaker, Tiny helpers maintainer, and DevRel at Checkly.