9

I would like to pass a named parameter to an npm run script so I can do something like the following:

"scripts":{
    "say-hello":"echo $greeting && ls"
 }

 npm run hello --greeting=hello

I'd like it to then put 'hello' in place of the $greeting variable, echo the command and then do the ls (this is obviously just a simple example of a chained command)

Ben
  • 16,124
  • 22
  • 77
  • 122

2 Answers2

10

Just found out that this works:

"scripts":{
  "say-hello" : "echo $npm_config_greeting && ls"
}

Edit:

Any environment variables that start with npm_config_ will be interpreted as a configuration parameter. For example, putting npm_config_foo=bar in your environment will set the foo configuration parameter to bar.

npm docs

Andres Zapata
  • 1,710
  • 1
  • 16
  • 32
robertklep
  • 198,204
  • 35
  • 394
  • 381
  • How did you get this to work? I'm trying and I can't figure it out. – JacobMiki Aug 06 '15 at 19:43
  • 1
    @JacobMiki [here's](https://gist.github.com/robertklep/12bb84f9cb4eed0d1da7) a minimal `package.json`, call with `npm run say-hello --greeting="hello world"` (`npm@2.11.2`) – robertklep Aug 06 '15 at 19:50
  • 1
    That's what I did, and still I get `$npm_config_greeting` echoed. Problem was, that I tried it on Windows and despite running it in bash, echo still expected variable to be in form `%npm_config_greeting%`. I'll delete my answer, as it is wrong. – JacobMiki Aug 07 '15 at 06:25
  • @JacobMiki oh right, Windows works differently when it comes to environment variables (which these are). Good point. – robertklep Aug 07 '15 at 07:25
  • @robertklep do you know if there's any work around or options for windows? – Ben Aug 11 '15 at 16:03
  • @Ben sorry, no, I don't have Windows myself so can't check for an alternative. – robertklep Aug 11 '15 at 16:05
  • In case anybody else is stuck with this - the only way I could get it to work with powershell (pwsh specifically) is to use `$env:variable` where variable is `npm_config_{name of variable passed to script as argument}` . Strangely obtuse. – dgo Dec 07 '20 at 22:19
2

Another way is to simply add the following '--' followed by your desired param(s). This would be for named parameters that '=' a value. Please note the underlying process in this example, a protractor call, expects a Url arg.

npm run e2e -- --Url="https://yoururlhere.com"
Kentonbmax
  • 938
  • 1
  • 10
  • 16