【问题标题】:How to implement multiple subcommands with Yargs?如何使用 Yargs 实现多个子命令?
【发布时间】:2020-01-24 10:16:03
【问题描述】:

我一直在尝试,但就是无法消化 Yargs 的 docs

我需要创建一组命令/子命令:

~$framework generate routed-module ModuleOne ModuleTwo ModuleThree --animation-style=bounce-up

//would call a handler with:
{ modules: string[], options: {animationStyle?: AnimationStyle}}
type AnimationStyle = 'bounce-up' | 'slide-left'

~$framework generate stateful-ui ModuleOne ModuleTwo ModuleThree
//would call a handler with:
{ modules: string[]}

~$framework init
//would just call a handler

我想要别名: ggenerate, rrouted-module, sstateful-ui

自动补全会很好。

这是我尝试过的,不知道从哪里开始:

  yargs
    .scriptName('elm-framework')
    .command({
      command: 'generate [moduleType] [moduleNames]',
      aliases: ['g'],
      describe: 'Generates a resource',
      handler: config.handleModuleGeneration,
      builder: {
        moduleType: {
          demand: true,
          choices: ['routed', 'stateful'] as const,
          default: 'routed',
        },
        moduleNames: {
          demand: true,
          array: true,
        },
      },
    })

谢谢!

(没有必要用打字稿做这个。我主要想了解如何使用库的api。)

【问题讨论】:

标签: javascript node.js typescript command-line-interface yargs


【解决方案1】:

使用this crucial piece of documentation 解决了这个问题:

  yargs
    .scriptName('framework')
    .command({
      command: 'generate [moduleType] [moduleNames...]',
      aliases: ['g'],
      describe: 'Generates a resource',
      handler: parsed => console.log('your handler goes here', parsed),
      builder: {
        moduleType: {
          demand: true,
          choices: ['routed', 'stateful'] as const,
          default: 'routed',
        },
        moduleNames: {
          demand: true,
          array: true,
        },
      },
    }).parse(process.argv.slice(2))

【讨论】:

    【解决方案2】:

    对我来说,实现这一目标的最佳方法是关注 this Github 问题,特别是 this comment 中的建议。 (另一个 builder 嵌套在命令 builder 中)。

    使用上述建议 ('generate [moduleType] [moduleNames...]') 的问题是您不能为不同的子命令使用不同的标志。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-04-18
      • 2023-03-23
      • 1970-01-01
      • 2022-11-11
      • 2014-06-19
      • 1970-01-01
      • 2022-07-05
      相关资源
      最近更新 更多