3

I have a simple app that I'm working on and that I invoke via an npm script. The script does two things. First it sets the NODE_ENV environment variable. Second, it calls node index.js.

I want the value of the NODE_ENV to be configurable via a command line argument, so I want something like this:

"scripts": {
    "test:integration": "cross-env NODE_ENV=%env% node index.js"
}

Then I can call it from the command line like so:

npm run test:integration --env=dev-integration

From what I have been reading, this should be possible given that NPM has a built in way to pass command line arguments to the scripts. This SO answer details it: https://stackoverflow.com/a/64694166/2951367.

However, I'm not able to get this to work. When I run this, I get the following error:

> cross-env NODE_ENV=%env% node index.js

WARNING: NODE_ENV value of '%env%' did not match any deployment config file names.
WARNING: See https://github.com/lorenwest/node-config/wiki/Strict-Mode
%env%

So I can see that the %env% argument is not resolving to what was passed in. I'm on windows, but I need this to work on linux as well so I thought cross-env might work, but it does not. I can't get this to work on windows either.

Any idea on how to get this to work?

Spark323
  • 1,525
  • 2
  • 16
  • 27
  • Consider the following solution that doesn't require any dependencies: **1)** Redefine your npm script as `"test:integration": "node -e \"const env = process.env; env.NODE_ENV = process.env.npm_config_env; require('child_process').execSync('node ./index.js', {env: env, stdio: 'inherit'});\""` **2)** Run the following command: `npm run test:integration --env=dev-integration`. – RobC May 27 '21 at 12:07

1 Answers1

0

The answer provided in the above comment is correct i.e. answer by @RobC With a few small tweaks in the syntax, I was able to fetch the env variable from cli. Thank you @RobC appreciate your help...

For reference below is the code I used to fetch ENV value from cli:

"test": "ts-node -e \\"const env = process.env; env.ENV = process.env.npm_config_env; require('child_process').execSync('npx wdio ./src/main/config/wdio.conf.ts', {env: env, stdio: 'inherit'});\\""

Run with the following command:

npm run test --env=test.

Note: I am using ts-node and executing WebdriverIO script.

Regards, Suraj Mishra