【问题标题】:How do I specify a default subcommand in yargs?如何在 yargs 中指定默认子命令?
【发布时间】:2016-07-07 22:14:01
【问题描述】:

我正在使用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(); }

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

有没有办法在 yargs 的语义范围内实现这一点? .command() 上的文档可能会更清楚。

【问题讨论】:

    标签: javascript node.js yargs


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      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;
      

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-07-05
      • 2022-12-15
      • 1970-01-01
      • 1970-01-01
      • 2020-05-07
      • 2018-01-03
      • 1970-01-01
      • 2011-09-15
      相关资源
      最近更新 更多