主题
基于inquirer命令行交互工具封装
依赖
inquirer@^8.0.0 一个常见命令行交互的js库
注意, inquirer
从v9 版本开始就不在支持commonjs规范, 只能用esm规范, 因此根据官方提示, 若要用commonjs规范, 只能安装v8版本, 下面是官方的提示
代码实现
javascript
const inquirer = require("inquirer");
/* 数据源配置 */
const templateTypes = {
name: "clientType",
message: "Please choice your client type", // 问询话语
choices: { // 有choices说明可以继续询问选择
nodejs: { // nodejs是 choices中每一项的value值
showName: "Nodejs application", // 选项展示的名称 (label)
With: ".easy-template-node", // 模板下载到计算机用户目录的目录名
TemplateUrl: "", // 模板所在仓库的下载链接(gitlab/github) 仓库应该是publish的, 否则下载会出错
},
websit: {
showName: "Web application",
name: "websitType",
message: "Please select the type of template you want to create",
choices: {
template3Admin: {
showName: "[admin] Vue3 + Element-plush + Typescript",
With: ".easy-template3-admin",
TemplateUrl: "",
},
template2Admin: {
showName: "[admin] Vue2 + ElementUI",
With: ".easy-template2-admin",
TemplateUrl: "",
},
},
},
},
};
// 获取用户选择
async function getUserChoices(obj) {
if ("choices" in obj) {
const { name, message, choices } = obj;
const actionObj = await inquirer.prompt([
{
type: "list",
name,
message,
choices: Object.keys(choices).map((value) => {
return { name: choices[value].showName, value };
}),
},
]);
const action = actionObj[name];
return await getUserChoices(choices[action]);
} else {
const { With, TemplateUrl } = obj;
return { With, TemplateUrl };
}
}
module.exports = async () => await getUserChoices(templateTypes);