ThePrince
ThePrince

Reputation: 890

npm Windows cmd syntax for passing environment variables (not recognized as internal or external command)

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.

Upvotes: 3

Views: 1958

Answers (2)

Viral Patel
Viral Patel

Reputation: 1166

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

Upvotes: 2

Trott
Trott

Reputation: 70163

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.

Upvotes: 3

Related Questions