1

I have few npm scripts in my package.json as:

"scripts": {
  "serve-india-local": "ng serve --project pro-india -c local",
  "serve-india-stag": "ng serve --project pro-india -c stag",
  "serve-india-prod": "ng serve --project pro-india -c prod",
  ...
}

Similarly for brazil

"scripts": {
  ...
  "serve-brazil-local": "ng serve --project pro-brazil -c local",
  "serve-brazil-stag": "ng serve --project pro-brazil -c stag",
  "serve-brazil-prod": "ng serve --project pro-brazil -c prod"
}

And similarly, I can have a few more scripts for different countries and configs.

I want to reduce this to a single script where I can take just 2 params:

  • countryName
  • config

So the final script should look something like this:

"serve-india-prod": "ng serve --project pro-$countryName -c $config"

Can someone help me to achieve this ?

RobC
  • 22,977
  • 20
  • 73
  • 80
Varun Sukheja
  • 6,170
  • 5
  • 51
  • 93
  • this is helpful https://stackoverflow.com/a/25356509/6885735 – Praveen Soni Sep 22 '19 at 13:25
  • On _*nix_ platforms npm uses `sh` as the default shell, therefore you can wrap your npm script in a shell function and reference the two arguments (i.e. `countryName` and `config`) using the `$1` and `$2` positional parameter(s). However if your want a cross-platform solution (i.e. one that also works with the Windows `cmd` shell) then you'll need to utilize a _node.js_ helper script instead. See my answer [here](https://stackoverflow.com/questions/51388921/pass-command-line-args-to-npm-scripts-in-package-json/51401577#answer-51401577.) for further understanding. – RobC Sep 22 '19 at 15:53
  • For instance; utilizing a _*nix_ shell function your npm-script can be defined as: `"serve": "func() { ng serve --project \"pro-${1}\" -c \"${2}\"; }; func"`. Then you invoke the command e.g. `npm run serve brazil prod` or e.g. `npm run serve india local` etc... – RobC Sep 23 '19 at 10:08
  • You can also provide a [default-value](https://stackoverflow.com/questions/9332802/how-to-write-a-bash-script-that-takes-optional-input-arguments#answer-9333006) for the `$1` and `$2` positional parameters. For instance if you change your npm-script to: `"serve": "func() { ng serve --project \"pro-${1:-india}\" -c \"${2:-prod}\"; }; func"`. Now if you invoke the npm script by running the command without any arguments e.g. `npm run serve` it will default to `pro-india` and `prod`. Yet when you run the command with arguments e.g. `npm run serve brazil prod` it will use `pro-brazil` and `prod`. – RobC Sep 23 '19 at 10:26

1 Answers1

0

you can easily accomplish this with shell variables

in package.json under scripts, include your npm script for example

{ 
    "scripts":{
     "serve-prod": "ng serve --project pro-$countryName -c $config"
    }
}

and in cli run as countryName=india config=local npm run serve-prod

this will not work well with cross platform, but you can use cross-env or cross-var

Praveen Soni
  • 771
  • 8
  • 21