3

我是指挥官的新手,我正在尝试实现这样的命令树:

|- build
|    |- browser (+ options)
|    |- cordova (+ options)
|    |- no subcommands, just options
|- config
|    |- create (+ options)

是否可以将这些命令拆分为多个文件,例如有点像这样:

中央档案:

const program = new commander.Command();
program.command('build').description(...);
program.command('config').description(...);

构建命令文件:

program.command('browser').description(...);
program.command('cordova').description(...);
program.option(...);

配置命令文件:

program.command('create').description(...);

我知道 Git-Style 子命令,但这些似乎需要可执行文件(我只有常规 JS 文件)

4

2 回答 2

6

Commander 中明确支持带有.js文件扩展名的独立子命令“可执行”文件,无需设置文件权限等以使其在命令行上直接可执行。

pm.js

const commander = require('commander');
const program = new commander.Command();
program
  .command('build', 'build description')
  .command('config', 'config description')
  .parse(process.argv);

pm-config.js

const commander = require('commander');
const program = new commander.Command();
program
  .command('create')
  .description('create description')
  .action(() => {
    console.log('Called create');
  });
program.parse(process.argv);
$ node pm.js config create
Called create
于 2019-08-21T20:38:15.563 回答
0

他们的文档中有一个示例:

const commander = require('commander');
const program = new commander.Command();
const brew = program.command('brew');
brew
  .command('tea')
  .action(() => {
    console.log('brew tea');
  });
brew
  .command('coffee')
  .action(() => {
    console.log('brew coffee');
  });

示例输出:

$ node nestedCommands.js brew tea
brew tea

https://github.com/tj/commander.js/blob/master/examples/nestedCommands.js

于 2021-04-21T00:12:08.570 回答