Run npm script with optional params

Viewed 501

I want to run a npm script which accepts optional params, and has a fallback for a default values for params that were not passed,

for example:

I have this "example" script defined in my pacakge.json:

  "scripts": {
     "example": "echo input"
  },

I want to pass in the "input" as a parameter meaning:

If I run npm run example --input=true then it'll output true

If I run npm run example without params then it'll output false

I modified my pacakge.json to accept the input parameter:

  "scripts": {
     "example": "echo %npm_config_input%"
  },

now when I run npm run example --input=true or npm run example --input=false I get 'true' or 'false' respectively, but when I run npm run example the result I get is %npm_config_input%.

I want to give the param a default value so that when its not passed in explicitly - the default value will be used, something similar to :

  "scripts": {
     "example": "echo %npm_config_input% || 'false'"
  },

So that running npm run example will result in 'false'

Is this possible?

1 Answers

You can achieve it using the https://www.npmjs.com/package/@naholyr/cross-env package, which supports default values for variables. On top of that, it will make your script OS-agnostic. Here's how:

"scripts": {
    "example": "cross-env INPUT=${npm_config_input:false} npm run _example",
    "_example": "cross-env command $INPUT"
},

For a reason yet unknown to me, using echo as the command will not print the variable value. But I'm successfully using this pattern to run sass with arguments, and fallback values, if no arguments are passed.

Related