Lerna脚手架搭建(十四):commander 脚手架命令注册

本文最后更新于:2023年8月21日 上午

一、方法一:command 注册命令 👈

1
2
3
4
5
6
7
const clone = program.command('clone <source> [destination]');
clone
.description('clone a repository')
.option('-f, --force', '是否强制克隆')
.action((source, destination, cmdObj) => {
console.log('do clone', source, destination, cmdObj, force);
});

二、方法二:addCommand 注册命令 👈

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
const service = new commander.Command('service');
service
.command('start [port]')
.description('start service at some port')
.action((port) => {
console.log('do service start', port);
});

service
.command('stop')
.description('stop service')
.action(() => {
console.log('stop service');
});

program.addCommand(service);

三、命令监听 👈

1
2
3
4
5
6
7
8
9
program
.arguments('<cmd> [options]')
.description('test command', {
cmd: 'command to run',
options: 'options for command',
})
.action(function(cmd, options){
console.log(cmd, options);
});

四、自定义 help 信息 👈

1
2
3
4
5
6
7
program.helpInformation = function() {
return '';
}

program.on('--help', function() {
console.log('your help information');
});

五、实现 debug 模式 👈

1
2
3
4
5
program.on('option:debug', function() {
if (program.debug) {
process.env.LOG_LEVEL = 'verbose';
}
});

六、对未知命令监听 👈

1
2
3
4
5
6
program.on('command:*', function(obj) {
// console.log(obj);
console.log('未知的命令:' + obj[0]);
const availableCommands = program.commands.map(cmd => cmd.name());
console.log('可用命令:' + availableCommands.join(','));
});

Lerna脚手架搭建(十四):commander 脚手架命令注册
https://blog.xuven.xyz/post/ScaffoldingOrderRegistration/
作者
Xuven Li
发布于
2022年5月6日
许可协议