About the Project
使用commander + inquirer 封装的终端问询式命令系统,可配合项目模版,快速完成各种前端脚手架cli。
项目仓库地址 github.com/Blackgan3/c… 下载即可使用。
工具简介
commander
进行终端命令设定,通过command,options, action方法链式实现特定命令的处理。
具体使用地址请看TJ 项目 github.com/tj/commande…
使用示例:
const program = require('commander');
program.command("init")
.alias("i")
.description("init a new project")
.action(async function(){
await initAction();
})
.on('--help', () => {
console.log();
console.log('Examples:');
console.log(' # create a new project');
console.log();
});
inquirer
使用inquirer来做用户与终端的问询交互以及用户输入信息的采集。
使用inquirer来完成输入框,选择框,确认按钮等终端流程表单的实现。
具体文档地址:github.com/SBoudrias/I…
inquirer的问询命令使用需要进行较多参数的传递,且开发使用语义性不强,所以我们在inquirer的基础上进一步封装,比如终端的输入节点:
var inquire = require('inquirer');
class InputNode {
constructor (title, config) {
this.title = title;
this.config = config || {};
}
async run() {
const { title, config } = this;
const {value} = await inquire.prompt([{
type: 'input',
name: 'value',
message: title,
validate: config.validate
},]);
return value;
}
}
module.exports = InputNode;
使用起来就可以这样:
const projectDesc = await Inquirer.InputNode('请输入项目描述');
比原来写法更简洁,同时更有语义。
以类似的封装方式,我们封装confirmNode, checkboxNode,listNode等节点。然后根据不同的脚本命令开发不同的流程。我们以 init 命令为例子:
1,h5-cli init
2, 选择初始化项目模版
3,选择模版配置(比如是否需要redux)
4,输入项目名称
5,输入项目描述
6,是否需要自动创建git远程仓库
大概的语义化代码:
const { templateId, url, cmd } = await Inquirer.ListNode('请选择项目模版', templateChoiceList);
let reactTemplateConfig = {};
if (templateId === templateIdEnum.react) {
reactTemplateConfig = await this.getReactTemplatePluginConfig();
}
// 获取当前用户git信息
// 输入项目名称(判断名字,仅支持英文)
const projectName = await Inquirer.InputNode('请输入项目名称', {
validate: function (value) {
if (String(value).length > 0) {
return true;
}
return '请输入项目名称';
}
});
const projectDesc = await Inquirer.InputNode('请输入项目描述');
// 输入仓库地址
const projectGitUrl = await Inquirer.InputNode('请输入项目git仓库地址');
if (!projectGitUrl) {
const needAutuGitUrl = await Inquirer.ConfirmationNode('是否需要自动生成git仓库');
if (needAutuGitUrl.value) {
// 根据自己业务自动生成仓库
}
}
具体代码可以在 项目中查看
根据问询命令获取的参数,我们可以去从远程仓库或者是本地文件夹选择 模版文件,然后根据用户的配置去生成初始化项目。
同理,同一个流程,也可以去实现 dev, publish等命令。