admin管理员组

文章数量:1401673

I'm using yargs to create a build tool with submands for "build", "link", "clean", etc.

I'd like to be able to type ./build.js with no arguments and invoke the "build" submand handler as a default.

I was able to do it thusly:

var argv = yargs
  .usage("I am usage.")
  mand('bundle', 'Create JS bundles', bundle)
  mand('link', 'Symlink JS files that do not need bundling', link)
  mand('clean', 'Remove build artifacts', clean)
  mand('build', 'Perform entire build process.', build)
  .help('help')
  .argv;
if (argv._.length === 0) { build(); }

But it seems a bit hacky to me, and it will likely cause problems if I ever want to add any additional positional arguments to the "build" submand.

Is there any way to acplish this within the semantics of yargs? The documentation on mand() could be more clear.

I'm using yargs to create a build tool with submands for "build", "link", "clean", etc.

I'd like to be able to type ./build.js with no arguments and invoke the "build" submand handler as a default.

I was able to do it thusly:

var argv = yargs
  .usage("I am usage.")
  .mand('bundle', 'Create JS bundles', bundle)
  .mand('link', 'Symlink JS files that do not need bundling', link)
  .mand('clean', 'Remove build artifacts', clean)
  .mand('build', 'Perform entire build process.', build)
  .help('help')
  .argv;
if (argv._.length === 0) { build(); }

But it seems a bit hacky to me, and it will likely cause problems if I ever want to add any additional positional arguments to the "build" submand.

Is there any way to acplish this within the semantics of yargs? The documentation on .mand() could be more clear.

Share Improve this question asked Jul 7, 2016 at 22:14 TedwardTedward 3234 silver badges6 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 7

As mented by @sthzg, you can have default mands now:

const argv = require('yargs')
  .mand('$0', 'the default mand', () => {}, (argv) => {
    console.log('this mand will be run by default')
  })

Yargs doesn't seem to provide this functionality by itself. There is a third party package on NPM that augments yargs to do what you want. https://www.npmjs./package/yargs-default-mand

var yargs = require('yargs');
var args = require('yargs-default-mand')(yargs);

args
  .mand('*', 'default mand', build)
  .mand('build', 'build mand', build)
  .args;

本文标签: javascriptHow do I specify a default subcommand in yargsStack Overflow