npm script pass parameters/arguments to node script using yargs

As of [email protected], you can use custom arguments when executing scripts. The special option -- is used by getopt to delimit the end of the options. npm will pass all the arguments after the -- directly to your script:

npm run test -- --grep="pattern"

https://docs.npmjs.com/cli/run-script


I'm not sure that it matters where the variables are added on the command line, and if this is of no concern to you, then this works:

//package.json
{
  "name": "npm-test",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {},
  "scripts": {
    "start": "node index.js"
  },
  "author": "",
  "license": "ISC"
}    

Your JS file:

//index.js
console.log('myvar', process.env.myvar);    

And your command line command:

myvar="hello world" npm run start    

So in the end, just prefix your npm script command with your argument list.