扩展和子命令插件机制-fe-robot
hugh 的个人博客 2020-03-31 22:29:09 fe-robotplugin前端
# 功能描述
plugin 机制旨在扩展 fe-robot,我们可以通过安装或卸载插件来让我们的小机器人更智能
安装目录为 <home>/.fe-robot/plugins
# install
# 参数
plugin: 插件名称, 可在 npm 市场搜索 fe-robot-plugin(插件名称需以 fe-robot-plugin 为前缀)
# uninstall
# 参数
plugin:插件名称,支持 fe-robot-plugin-{name}(或直接输入 name) 来卸载安装
# 使用范例
fe-robot install fe-robot-plugin-example
fe-robot uninstall example
fe-robot uninstall fe-robot-plugin-example
1
2
3
2
3
# 如何写一个扩展型插件
- npm init, 初始化一个项目
- 入口文件中返回如下对象即可
module.exports = {
desc: "这是一个plugin demo",
options: [{optStr: '-i, --it <it>', desc: 'show it'}], // 该项为接受的参数
action: (source, {it}, config) => { // source为一个可选的参数,表示插件本身可以接受一个或多个可选参数, config为全局配置,可自定义覆盖
console.log(source, it, config)
}
}
1
2
3
4
5
6
7
2
3
4
5
6
7
- 调用测试
fe-robot example a -i b // [a], b, configObj
fe-robot example -i b // [], b, configObj
fe-robot example a c -i b // [a,c],b,configObj
1
2
3
2
3
# 如何写一个子命令型插件
- npm init, 初始化一个项目
- 入口文件中返回如下对象即可
const commander = require('commander');
module.exports = {
desc: "这是一个ext command demo",
extend: (command, args, config) => {
const program = new commander.Command();
program
.name(command)
.usage("[options] command")
program
.command('serve')
.option('--port <port-number>', 'specify port number', 80)
.action((cmd) => {
if (cmd.debug) {
console.log('Options:');
console.log(cmd.opts());
console.log();
}
console.log(`Start serve on port ${cmd.port}`);
});
// error on unknown commands
program.on('command:*', function () {
console.log("当前命令还不支持哦",program.args.join(' '));
process.exit(1);
});
program.parse(process.argv)
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
- 调用方式
fe-robot testcommand -h // 展示帮助信息
fe-robot testcommand serve // 调用子命令内的命令
1
2
2