named parameter to npm run script
Asked Answered
T

2

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)

Trippet answered 6/8, 2015 at 19:1 Comment(0)
S
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

Stoneman answered 6/8, 2015 at 19:13 Comment(7)
How did you get this to work? I'm trying and I can't figure it out.Aboral
@Aboral here's a minimal package.json, call with npm run say-hello --greeting="hello world" ([email protected])Stoneman
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.Aboral
@Aboral oh right, Windows works differently when it comes to environment variables (which these are). Good point.Stoneman
@Stoneman do you know if there's any work around or options for windows?Trippet
@Trippet sorry, no, I don't have Windows myself so can't check for an alternative.Stoneman
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.Aerolite
E
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"
Evertor answered 28/5, 2019 at 14:3 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.