Lorenz Meyer
Lorenz Meyer

Reputation: 19945

Environment variable expansion not longer works in npm run on Windows

I have npm scripts that use environment variables. Here is an excerpt of package.json:

"scripts": {
    "staging": "npm run deploy -env=staging",
    "deploy": "winrs /r:intranet /d:F:\\wwwintranet\\deploy npm run build -env=%npm_config_env%",

Until now, -env=%npm_config_env% was expanded to -env=staging or whatever. Suddenly it stopped working. Probably this is due to an update to npm from 6.x to 7.x.

When I test with "deploy": "set & winrs /r:intranet /d:F:\\wwwintranet\\deploy npm run build -env=%npm_config_env%", I can confirm that the variable is still set.

As a temporary solution, downgrading npm to version 6.x (npm install -g npm@6) helped. Nevertheless, I need a solution that will work also in the future.

How can I enable variable expansion again for npm 7.x ? Or what are the alternatives for passing environment variables with npm 7.x ?

Edit

This was a bug in npm 7.5.x. It is fixed in npm 7.7.0 and above (see https://github.com/npm/cli/issues/2731)

Upvotes: 0

Views: 1175

Answers (1)

Trott
Trott

Reputation: 70163

Failure to expand environment variables on Windows appears to be a recent high-priority known bug in the npm CLI.

There are several options to use as a workarounds until a fix is released.

  • You can downgrade to version 6.x until this is fixed.
  • This won't work for your specific case (see below), but for most cases, you can use npx to use npm@6:
npx -p npm@6 npm run deploy
  • You can try downgrading to an earlier version of 7.x to see if the bug has always existed in 7.x or not. Start with 7.0.0 and go from there.

The npx suggestion won't work here because deploy invokes npm itself and that will use npm from your PATH which is npm@7. But for generic cases where you need to invoke an old version of npm in narrow cases, that will work.

Upvotes: 1

Related Questions