Search code examples
javascriptyargs

Yargs - can I get "rest" arguments?


I need to process specific option, and pass all other arguments further as an array.

For example:

I call the script like this: node script.js --one 1 --two 2 --three 3

const args = yargs(argv).demandOption("one").string("one").argv;
console.log(args.one);

const rest = ???
console.log(rest);

Should write:

1
["--two", 2, "--three", 3]

Is this doable with yargs? Something like the _ value, but _ only contains non-option values so I can't use that.


Solution

  • Found the answer thanks to amazing yargs' test suite: https://github.com/yargs/yargs/blob/main/test/yargs.cjs#L1841

    I just need to configure the yargs to pass unknown options to _ too:

    const args = yargs(argv)
        .parserConfiguration({'unknown-options-as-args': true})
        .demandOption("one")
        .string("one")
        .argv;