How to pass and reuse parameters in multiple npm scripts?

Hey folks, I’m trying to figure out how to run multiple scripts with a single parameter. Here’s what I want to do:

I’ve got an all script that runs two other scripts, code1 and code2. I want to pass one parameter to all and have both code1 and code2 use that same parameter. Something like this:

{
  "scripts": {
    "all": "npm run firstScript -- $PARAM && npm run secondScript -- $PARAM"
  }
}

So when I run npm run all -- myValue, it should basically do:

  1. npm run firstScript -- myValue
  2. npm run secondScript -- myValue

Is there a way to set this up in the package.json? I’ve tried a few things but can’t get it working. Any help would be awesome!

I’ve encountered this issue before, and there’s a neat solution using cross-env that works across different operating systems. Here’s what you can do:

First, install cross-env as a dev dependency:

npm install --save-dev cross-env

Then, modify your package.json scripts like this:

“scripts”: {
“all”: “cross-env PARAM=$npm_config_param npm run firstScript && cross-env PARAM=$npm_config_param npm run secondScript”,
“firstScript”: “echo First script with param $PARAM”,
“secondScript”: “echo Second script with param $PARAM”
}

Now you can run npm run all --param=myValue and both scripts will receive the parameter. This approach is more robust and works consistently across Windows, macOS, and Linux.

While the previous solutions are valid, I’d like to suggest another approach using npm-run-all. This package simplifies running multiple npm scripts sequentially or in parallel.

First, install npm-run-all:

npm install --save-dev npm-run-all

Then, update your package.json:

{
“scripts”: {
“all”: “run-s "firstScript:" "secondScript:"”,
“firstScript:": “echo First script with param”,
"secondScript:
”: “echo Second script with param”
}
}

Now you can run npm run all – myValue, and both scripts will receive the parameter. This method is clean, flexible, and works across different OS platforms without additional configuration.

hey SurfingWave, i’ve done smth similar before. try using $npm_config_param instead of $PARAM in ur scripts. like this:

“all”: “npm run firstScript --param=$npm_config_param && npm run secondScript --param=$npm_config_param”

then u can run it with npm run all --param=myValue. hope this helps!