const inquirer = require('inquirer')
const fs = require('fs')
const path = require('path')
const exec = require('child_process').exec;
const ejs = require('ejs')

inquirer 一个用户与命令行交互的工具

type:表示提问的类型,包括:input, confirm, list, rawlist, expand, checkbox, password, editor;
name: 存储当前问题回答的变量;
message:问题的描述;
default:默认值;
choices:列表选项,在某些type下可用,并且包含一个分隔符(separator);
validate:对用户的回答进行校验;
filter:对用户的回答进行过滤处理,返回处理后的值;

语法结构

const inquirer = require('inquirer');

const promptList = [
// 具体交互内容
];

inquirer.prompt(promptList).then(answers => {
console.log(answers); // 返回的结果
})
module.exports = [
{
type: "input",
message: "请输入你的项目名称",
name: "projectName",
validate(val) {
if (val.trim() == '') {
return '项目名称不能为空'
} else {
return true
}
}
},
{
type: "list",
message: "请选择你的框架",
name: "frame",
choices: [
{
name: "Vue",
value: "Vue"
},
{
name: "Angular",
value: "Angular"
},
{
name: "React",
value: "React"
},
{
name: "jQuery",
value: "jQuery"
}
],
filter(value) {
return value.toLocaleLowerCase()
}
},
{
type: "confirm",
message: "是否需要生成html文件",
name: "isHtml",
default: true,
},
{
type: "list",
message: "请选择你的包管理工具",
name: "package",
choices: [
{
name: "Npm",
value: "Npm"
},
{
name: "Yarn",
value: "Yarn"
}
],
filter(value) {
return value.toLocaleLowerCase()
}
},

]

2 fs 操作文件

fs.mkdir 创建文件夹  三个参数 url  权限=0777  回调

fs.writeFile 写入文件 三个参数 url 写入的参数 回调

3 ejs

ejs.render 两个参数 文件地址,options 修改的值

条件语法

<% if (frame == 'vue') { %>
"vue":"2.6.0"
<% } %>

插值 语法

<%= packageName %>

4 exec

exec(`${result.package} install`, { cwd: result.projectName })

用来执行shell脚本命令

整体代码

const inquirer = require('inquirer')
const fs = require('fs')
const path = require('path')
const exec = require('child_process').exec;
const ejs = require('ejs')
const question = require('./question')
const PACKAGEJSON = './package.json'
const getEjsTemplate = (path) => {
return fs.readFileSync(`./template/${path}`).toString()
}
inquirer.prompt(question).then(result => {
fs.mkdir(result.projectName, '0777', () => {
const packageJson = getEjsTemplate('package.ejs')
const json = ejs.render(packageJson, {
packageName: result.projectName,
frame: result.frame
})
fs.writeFile(path.join(__dirname, result.projectName, PACKAGEJSON), json, () => {
const html = ejs.render(getEjsTemplate('html.ejs'))
result.isHtml && fs.writeFile(path.join(__dirname, result.projectName, './index.html'), html, () => {

})
exec(`${result.package} install`, { cwd: result.projectName })
})
})
})