如何在 yargs 中指定默认子命令?

How do I specify a default subcommand in yargs?

我正在使用 yargs 创建一个带有 "build"、"link"、"clean" 等子命令的构建工具

我希望能够不带参数地键入 ./build.js 并默认调用 "build" 子命令处理程序。

我是这样做到的:

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(); }

但这对我来说似乎有点老套,如果我想向 "build" 子命令添加任何额外的位置参数,它可能会导致问题。

有没有办法在 yargs 的语义中完成这个? .command() 上的文档可能更清楚。

Yargs 本身似乎不提供此功能。 NPM 上有一个第三方包可以增强 yargs 来做你想做的事。 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;

正如@sthzg 所说,您现在可以 default commands

const argv = require('yargs')
  .command('[=10=]', 'the default command', () => {}, (argv) => {
    console.log('this command will be run by default')
  })