Package-agnostic scripts with Node.js

How to simplify running scripts in NPM, Yarn and PNPM

If you have custom scripts in your package.json-file, like “npm my-script” or “yarn my-script”, they will only work with the package manager you define. But NPM offers an API to call the current executable every time, without explicitly specifying it.

{
  "scripts": {
    "cleanup": "./clean-up.js",
    "copy": "./copy.js",
    "prepare": "npm run cleanup && npm run copy"
  }
}

Using $npm_execpath

By using the string “$npm_execpath” instead of “npm” or “yarn” (or another package manager like “pnpm”), this script will work with every package manager, no matter what the current developer has used to call the original script.

{
  "scripts": {
    "cleanup": "./clean-up.js",
    "copy": "./copy.js",
    "prepare": "$npm_execpath run cleanup && $npm_execpath run copy"
  }
}

Is it compatible on all machines?

Sadly, using “$npm_execpth” to make scripts work with any package manager doesn’t reliably work on machines that have Windows installed.

What is the most reliable way to call scripts in package.json?

Therefore, the most reliable way to call your custom scripts in the package.json-file is still to explicitly define the package manger executable and ensure that your team only uses that one.

It’s better on devices that don’t run Windows, where you can use “$npm_execpath” to reliably execute those scripts.

Suggestions

Related

Addendum

Languages