Costa Michailidis
Costa Michailidis

Reputation: 8178

How to provide default parameter value to npm script?

I have this in my package.json file:

scripts: { 
  "echo": "echo ${1-'/*'}"
}

Then when I run npm run echo I get /* which is what I want (It denotes all paths from the root. That's the default.)

But, when I run npm run echo /salad, I get /* /salad which is not helpful. It seems to be using the default, adding a space, and then adding the parameter.

How do I get just /salad when I provide a parameter, and /* when I don't provide a parameter?

Upvotes: 4

Views: 1823

Answers (1)

guyot
guyot

Reputation: 363

npm script arguments are just appended to the end, so they will not correctly resolve numeric variables like $1.

To make such variables resolve, you can wrap your script in a shell function and then execute the function. Try this:

scripts: { 
  "echo": "run(){ echo ${1-'/*'}; }; run"
}

Alternatively, just use named variables in your script instead of numeric ones.

Upvotes: 6

Related Questions