npm script pass parameters/arguments to node script using yargs

Simon picture Simon · Jul 10, 2017 · Viewed 7.8k times · Source

Is it possible to call out to retrieve a key from yargs when using as a npm script argument?

User types in the OSX terminal:

npm run scaffold --name=blah

which executes in package.json:

"scaffold" : "node ./scaffold/index.js -- "

This results in

const yargs = require('yargs').argv

if (yargs) {
  console.log(yargs);
  console.log(yargs.name);
  process.exit(1)
}
...
result:
{ _: [], '$0': 'scaffold/index.js' }
undefined

This only works if I hard code in package.json "scaffold" : "node scaffold/index.js --name=blah", but I need this to be configurable.

As I stated I am using args, as it appears to make it easy to retrieve keys by name ( as opposed to an array ). Open to suggestions.

What am I missing?

update 11-07-2017 Related: Sending command line arguments to npm script

However, passing in the commandline 1: npm run scaffold name=hello OR 2: npm run scaffold --name=hello yields:

1: { _: [], '$0': 'scaffold/index.js' }
2: { _: [ 'name=hello' ], '$0': 'scaffold/index.js' }

Still can't see a way to retrieve the yargs.name property. Still undefined.


Update 13-07-2017

For the time being, I have given up. It just seem impossible. I run the script manually in the terminal. E.g.

node ./scaffold/index.js --name=blah 

Image below shows executing of a node script directly as opposed to running through npm scripts. I have added https://www.npmjs.com/package/nopt node module to see if it helps ( it doesn't ). process.argv.name is still undefined when running through npm scripts.

enter image description here


Update 18-07-2017

Added github example: https://github.com/sidouglas/stackoverflow-node-arguments


Update 24-07-2017

Adding the variables before the start of the command works myvar="hello npm run scaffold as opposed to npm run scaffold myvar="hello world"

Answer

sabrehagen picture sabrehagen · Jul 13, 2017

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