Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Syntax (windows and linux) for multiple commands using Node cross-env

I'm taking a look at a project that has this line in it's package.json to run Karma tests

 "scripts": {
        "test": "NODE_ENV=test karma start karma.conf.js",

This doesn't work in Windows when I try "npm test".

I gather this is because this is a *nix syntax. And, in fact, if I change it to

 "scripts": {
        "test": "set NODE_ENV=test && karma start karma.conf.js",

the tests start when I run npm test.

Looking around, the optimal solution appears to be to use the cross-env package and rewrite it like

 "scripts": {
        "test": "cross-env NODE_ENV=test && karma start karma.conf.js",

So I get the cross-env will take care of the "set NODE_ENV" part to work on multiple OSes, but it's the "&&" part I'm questioning.

Do I leave the "&&" between the commands when using cross-env? Will that work in windows and linux?

like image 391
Luke Avatar asked Oct 16 '25 13:10

Luke


1 Answers

Your cross-env example won't work, it should just be:

 "scripts": {
    "test": "cross-env NODE_ENV=test karma start karma.conf.js",

without the &&. The command to run comes immediately after you're done setting the variables.

I found your question by searching for how to set multiple variables with cross-env and also how to run multiple scripts/commands with cross-env. So to address the "multiple commands" part of your question:

Given these 2 test scripts:

a.js

console.log('a', process.env.TEST_VAR, process.env.TEST_VAR_2);

b.js

console.log('b', process.env.TEST_VAR, process.env.TEST_VAR_2);

You'll find if you have an && in the script in your package.json the subsequent scripts don't receive the variables. For example:

"scripts": {
    "check": "cross-env TEST_VAR=hello TEST_VAR_2=world node a.js && node b.js",

Running npm run check gives:

a hello world
b undefined undefined

You can solve this by having an extra script which runs the multiple commands and running that with cross-env:

"scripts": {
    "check": "cross-env TEST_VAR=hello TEST_VAR_2=world npm run check-real",
    "check-real": "node a.js && node b.js",

Now npm run check gives:

a hello world
b hello world
like image 69
antriver Avatar answered Oct 19 '25 04:10

antriver



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!