2

What is the syntax for writing this command line command on Windows cmd.

MY_ENV_VAR=2 npm run my_script

or

MY_VAR1=100 MY_VAR2=300 npm run my_script

Basically I am trying to set the environment variables on my script.

Inside my index.js, for example, I have:

const MY_VAR1 = process.env.MY_VAR1 || 200;

Every time I run this on Windows cmd, I get "MY_VAR1 not recognized as internal or external command".

I have looked everywhere on the internet - this syntax seems to work on Mac but not on Windows cmd.

Please tell me the equivalent on Windows.

Of course, running

npm run my_script

runs fine.

ThePrince
  • 818
  • 2
  • 12
  • 26
  • `MY_ENV_VAR=2 npm run my_script` is in Windows command prompt window `set "MY_ENV_VAR=2" & npm run my_script` and in a Windows batch file `set "MY_ENV_VAR=2" & call npm.cmd run my_script`. `MY_VAR1=100 MY_VAR2=300 npm run my_script` is in command prompt window `set "MY_VAR1=100" & set "MY_VAR2=300" & npm run my_script` and in a batch file is replaced again `npm` by `call npm.cmd`. See [single line with multiple commands using Windows batch file](https://stackoverflow.com/a/25344009/3074564). – Mofi Apr 08 '21 at 09:47

2 Answers2

3

The two options I've most seen are:

  1. Use Windows Subsystem for Linux. That will provide you with a shell where environment variables can be set the same was as on Linux. So MY_ENV_VAR=2 npm run my_script will work.

  2. Use cross-env. Then it's cross-env MY_ENV_VAR=2 npm run my_script.

Trott
  • 66,479
  • 23
  • 173
  • 212
  • 1
    Hey. cross-env did work, but the command you gave me results in "cross-env is not recognized as an internal or external command". So actually, the steps would be 1. npm i cross-env --save-dev. 2. in package.json script section, write: "build": "cross-env MY_ENV_VAR=2 nodemon ./app". 3. in command line write 'npm run build'. – ThePrince Apr 08 '21 at 06:13
2

Adding one more option for Windows. You can set the environment variables using set as follows.

set MY_VAR1=543

Then you'll get the value of MY_VAR1 in process.env.MY_VAR1 by running the npm run command.

npm run my_script

Or you can write the above two lines into single one using &&.

set MY_VAR1=543 && npm run my_script
Viral Patel
  • 1,104
  • 4
  • 7