NPM 7 - Pass Flags to Script

Viewed 732

In NPM prior to version 7, we were able to pass arbitrary flags to a package.json script using dollar-asterisk:

// package.json
"scripts": {
  "build": "npx pkg-bin build $*"
}

For example, if the above script is executed like this:

npm run build --OVERRIDE --versionNumber=1.2.3

The OVERRIDE and versionNumber flags were accessible via process.env.npm_config_argv.

However, in NPM 7, this feature appears to have been removed. The flags are still not present in process.argv (like always) but now npm_config_argv is also gone.

The values are now found on process.env as individual config values like this:

npm_config_override: 'true',
npm_config_versionnumber: '1.2.3'
npm_config_loglevel: 'error'

This presents a few problems:

  • Every other NPM config value also has its own npm_config_ key (like loglevel above), so it's impossible to tell which ones were passed as flags
  • There's no way to distinguish between flags that were passed with one hyphen vs. two hyphens
  • The letter casing (lower/upper/camel) doesn't match the value passed to the script

Is there a workaround for passing flags to a package.json script in NPM 7?

2 Answers

Since the release of npm 7.x several of the npm_* prefixed environment variables have been removed. Refer to rfc #0021 for further details.

Note, in the Downsides section of that rfc it states:

Some modules today use npm_config_argv. These will have to be updated to use other means to get this information.

Where the argv is being parsed in order to determine the command being run, the npm_command environ provides a safer approach.

Therefore the npm_command environment variable may be worth exploring. However, as noted in your comment it currently holds a value of exec only which suggests it has not yet been fully implemented.

did you try -- before providing the arguments to the script?

Any positional arguments are passed to the specified script. Use -- to pass --prefixed flags and options which would otherwise be parsed by npm.

For example:

npm run test -- --grep="pattern"

Source.

Related