为什么主要节点参数解析器使用链接语法?

Why do the major node arg parsers use chaining syntax?

两者 commander and yargs 都使用让人联想到 jQuery 的链接语法。

链接语法是创建库的时代的历史产物,还是有功能性动机?

正在尝试决定是否使用我喜欢的语法编写包装器。

指挥官:

program
  .option('-d, --debug', 'output extra debugging')
  .option('-s, --small', 'small pizza size')
  .option('-p, --pizza-type <type>', 'flavour of pizza');

program.parse(process.argv);

yargs:

yargs(hideBin(process.argv))
  .command('serve [port]', 'start the server', (yargs) => {
    yargs
      .positional('port', {
        describe: 'port to bind on',
        default: 5000
      })
  }, (argv) => {
    if (argv.verbose) console.info(`start server on :${argv.port}`)
    serve(argv.port)
  })
  .option('verbose', {
    alias: 'v',
    type: 'boolean',
    description: 'Run with verbose logging'
  })
  .argv

例如,他们可以改为接受一个大型配置对象,这看起来更符合习惯:

parse({
  options: {
    debug: {
      description: 'output extra debugging',
      alias: 'd'
    },
    small: {
      description: 'small pizza size',
      alias: 's'
    },
    ['pizza-type']: {
      description: 'flavour of pizza',
      alias: 'p'
    },
  }
})

此方法的名称为 fluent interface 并且广为人知,因为它简化了对同一对象的一堆方法的调用。 Martin Fowler 在 jQuery 出现之前就提到了这种方法。参见 Fluent interface

例如,将 C# 中的 LINQ 视为流畅接口原则的强大实现。