Home > Blockchain >  Scripts arguments starting with -- are removed
Scripts arguments starting with -- are removed

Time:05-18

In node 14 I had the following script

scripts: {
  "test": "node test.js",
}

Then I ran it with the following command npm run test -- --value '10' this gave the output

node test.js "--value" "10"

But when I switch to node 16 every argument that starts with -- gets removed

So whenI run npm run test -- --value '10' this gives the output

node test.js "10"

Where did "--value" go?

CodePudding user response:

I'm not sure 100% about the root cause, but I can now explain the semi-root causes and ways to work around it.

It appears that while on my machine there is only an npm.cmd file in C:\Program Files\nodejs, on yours there is also an npm.ps1 file. It appears this file is created only in some install/upgrade paths, and your node upgrade seems to cause this file to be created.

That means that when you run npm in PowerShell, it is invoking an ExternalScript and not an Application. For this reason, semantics for calling cmdlets apply to the invocation and not semantics for calling native commands/applications.

These semantics include the use of -- to stop parsing further arguments. That means that in this case PowerShell will consume the -- token so it never arrives to npm! And in turn, npm now being called with npm run test --value 10 without -- will swallow --value because it's considered an argument to npm and not to the script you want to invoke.

Quote from the docs:

The end-of-parameters token (--)

The end-of-parameters token (--) indicates that all arguments following it are to be passed in their actual form as though double quotes were placed around them. For example, using -- you can output the string -InputObject without using quotes or having it interpreted as a parameter

It doesn't state here that it applies only to cmdlets and external scripts but my testing showed that that's the case.

There are four possible solutions I can think of:

  • Create an alias to manually point npm to npm.cmd instead of npm.ps1: Set-Alias -Name npm -Value npm.cmd
  • Rename/remove npm.ps1 to make sure PowerShell uses npm.cmd instead
  • Add another -- in front which is consumed by PowerShell to allow the following -- to be consumed by npm: npm run test -- -- --value 10 or npm -- run test -- --value 10
  • Quote the --: npm run test '--' --value 10
  • Related