Search code examples
javascriptnode.jsyargs

How do I specify a default subcommand in yargs?


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

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

I was able to do it thusly:

var argv = yargs
  .usage("I am usage.")
  .command('bundle', 'Create JS bundles', bundle)
  .command('link', 'Symlink JS files that do not need bundling', link)
  .command('clean', 'Remove build artifacts', clean)
  .command('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" subcommand.

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


Solution

  • 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.com/package/yargs-default-command

    var yargs = require('yargs');
    var args = require('yargs-default-command')(yargs);
    
    args
      .command('*', 'default command', build)
      .command('build', 'build command', build)
      .args;