0

Here is my scripts object:

"scripts": {
    "version-update": "node version-generator.js",
    "build": "npm run version-update && webpack --mode production"
}

I want to pass some arguments to my version-update command on build command calling, like this:

npm run build -- --type=1

and fetch --type arg in my version-generator.js.

But when I did this, -- --type=1 only effects webpack --mode production and I can not achieve it in version-generator.js.

Behnam Azimi
  • 2,260
  • 3
  • 34
  • 52
  • The easiest way is using env var – ChunTingLin Nov 26 '19 at 12:44
  • 2
    Does this answer your question? [Pass command line args to npm scripts in package.json](https://stackoverflow.com/questions/51388921/pass-command-line-args-to-npm-scripts-in-package-json) – RobC Nov 26 '19 at 17:01

2 Answers2

0

Here's a not-so-pretty looking workaround that works only on linux.

  "scripts": {
    "version-update": "node version-generator.js",
    "build": "call_with_args() { npm run version-update -- \"$@\"; webpack --mode production \"$@\"; } && call_with_args"
  },
Nijraj Gelani
  • 1,446
  • 18
  • 29
-1

When you run npm run build -- --type=1 it's passed type=1 as argument to the script command build .

Based on the npm command syntax npm run <command> [-- <args>], What you want is similar to this:

"build": "npm run version-update -- <arg> && webpack --mode production"

Unfortunately npm does not have a built-in feature to achieve this. Note the -- is needed to separate the params passed to npm command itself and params passed to your script. And the arguments are passed to the END of a script but NOT into the MIDDLE. So, you could try the following:

"build": "webpack --mode production && npm run version-update --"
Jeff Pal
  • 1,519
  • 1
  • 17
  • 28
  • Thank you, I need to exec version-update before webpack – Behnam Azimi Nov 26 '19 at 12:59
  • [_"unfortunately npm does not have a built-in feature to achieve this"_ and _"to the END of a script but NOT into the MIDDLE"_](https://stackoverflow.com/questions/51388921/pass-command-line-args-to-npm-scripts-in-package-json#answer-51401577) - The _"Short Answer"_ section of my answer wasn't actually the solution. – RobC Nov 27 '19 at 16:47