Home > other >  How to pass r-value of an environment variable as a CLI argument for an NPM script
How to pass r-value of an environment variable as a CLI argument for an NPM script

Time:04-07

Goal: Is there a way or hack that lets me add r-value of an environment variable as a CLI argument for an NPM script without calling a separate script?

Example:

  • Script: "test:run": cypress run --spec 'tests/*' --env host=
  • Usage: npm run test:run localhost
  • Expectation: cypress run --spec 'tests/*' --env host=localhost

What I use currently is:

  • Script: "test:run": cypress run --spec 'tests/*' --env
  • Usage: npm run test:run host=localhost
  • Result: cypress run --spec 'tests/*' --env host=localhost

This works, but I'm wondering if there's a way to even omit adding host= in my command so I can just write the r-value, localhost for brevity.

CodePudding user response:

I don't think that what you want to achieve is currently possible how you want to achieve it, because of how npm breaks out command-line arguments. Anything passed in is appended as a separate "option", instead of just added to the existing string, which is the behavior you're currently seeing (npm run test:run localhost => cypress run --spec 'tests/*' --env host= localhost).

There are a few alternatives, which seem to be what you don't want to do, but you could create a separate script for that behavior.

"test:run": "cypress run --spec 'tests/*' --env"
"test:run:local": "npm run test:run host=localhost"

Or, you could declare the Cypress environment variable before the test command.

CYPRESS_HOST=localhost npm run test:run
  • Related