plop工具使用:自动生成模板代码
(一)大概的步骤:
1.npm安装
2.创建plopfile.js配置文件(配置与步骤3中文件的对应关系)
3.创建相关模板文件
4.package.json中配置运行命令
(二)具体操作如下:
1.安装
npm install --save-dev plop
2.根目录添加plopfile.js文件
function validate(v) { if (/[[\u4E00-\u9FA5]|[\uFE30-\uFFA0]|\s]+/.test(v)) { return "输入内容不能包含中文和空格"; } else { return true; } } module.exports = plop => { plop.setGenerator("vue", { description: "创建vue文件", prompts: [ { type: "input", name: "moduleName", message: "请输入模块名称", validate, }, { type: "input", name: "fileName", message: "请输入文件名称", validate, }, { type: "list", name: "path", choices: ({ moduleName, fileName }) => { return [`${moduleName}/${fileName}/index`, `${moduleName}/${fileName}`]; }, message: "请选择生成方式", }, { type: "list", name: "apiSty", choices: () => { return ["get_post", "restfule"]; }, message: "请选择生成API的风格,默认使用get_post风格", }, ], actions: (data) => { let { path, fileName } = data; let spePath = path.replace(/index$/, fileName); let apiTemplUrl = data.apiSty == "restfule" ? "plop-template/api_restful.hbs" : "plop-template/api_get_post.hbs"; // console.log(`output->path`, path) // console.log(`output->spePath`, spePath) const actions = [ { type: "add", path: `src/views/${path}.vue`, templateFile: "plop-template/vue.hbs", data, }, { type: "add", path: `src/api/${path}.ts`, templateFile: apiTemplUrl, data, }, { type: "add", path: `src/views/${spePath}.ts`, templateFile: "plop-template/vue-ts.hbs", data, }, ]; return actions; }, }); plop.setHelper("upperFirstCase", function (text) { return text.slice(0, 1).toUpperCase() + text.slice(1).toLowerCase(); }); }
3.根目录添加plop-template文件夹,按plopfile.js文件中配置的路径添加模板文件
4.package.json中配置运行命令
5.使用:
npm run plop