Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 641
Tedward Avatar asked Mar 09 '26 21:03

Tedward


1 Answers

As commented by @sthzg, you can have default commands now:

const argv = require('yargs')
  .command('$0', 'the default command', () => {}, (argv) => {
    console.log('this command will be run by default')
  })
like image 161
erandros Avatar answered Mar 11 '26 09:03

erandros