plop:可以通過命令行去生成、處理文件模板代碼等.
使用條件參考:項(xiàng)目的每個(gè)模塊的結(jié)構(gòu)骨架都非常相似构灸,引入模版內(nèi)容相同就可以使用Plop來實(shí)現(xiàn)自動(dòng)化了盅安,Plop旨在根據(jù)模板文件自動(dòng)化創(chuàng)建組件吨凑。
一耕捞、安裝plop
- 安裝到項(xiàng)目
npm install --save-dev plop
- 全局安裝plop(可選负溪,建議安裝方便使用)
npm install -g plop
如果沒有全局安裝plop逃沿,那么要在package.json中的script中增加腳本命令:
"scripts": {
"p": "plop"
},
二婴渡、創(chuàng)建路由Generator
1、 根目錄創(chuàng)建一個(gè)plop-template
文件夾凯亮,并創(chuàng)建一個(gè)router
目錄作為路由的generator
,并創(chuàng)建generator
的js
文件和hbs模板(Handlebars模板語法)
三边臼、 generator之plop.js編寫
- !!
plop.js
即prompt.js
文件
const {notEmpty} = require('../util.js');
module.exports = {
description: 'generate a controller', //描述這個(gè)generate的作用
prompts: [{
type: 'input', // 問題的類型
name: 'pathName', // 問題對應(yīng)得到答案的變量名,可以在acitons中使用該變量
message: '文件名稱', // 在命令行中的問題
validate: notEmpty('pathName')
}],
actions: (data) => {// 這里可以通過data獲取輸入的pathname
let name = data.pathName.split('/');
name = name[name.length - 1];
name[0] = name[0].toLocaleUpperCase();
const actions = [
{
type: 'add', // 操作類型 添加文件
path: `app/controller/${data.pathName}.ts`, //添加的文件的路徑
templateFile: 'dev-scripts/plop-templates/router/index.hbs', //模版文件的路徑
data: {
name
}
}
];
return actions;
}
};
- hbs模板文件
!!模版文件作用:編寫生成文件的模版內(nèi)容假消,可自己根據(jù)項(xiàng)目需求進(jìn)行定義柠并。
require('module-alias/register');
import BaseController from '@base/baseController';
import { AController } from '@lib/aRouter';
export default class {{ name }}Controller extends BaseController {
}
四、plop使用
在項(xiàng)目的根目錄下創(chuàng)建plopfile.js文件
- 設(shè)置到plopfile.js
const routerGenerator = require('./dev-scripts/plop-templates/router/prompt');
module.exports = function (plop) {
plop.setGenerator('router', routerGenerator);
};
五富拗、 運(yùn)行plop臼予、生成文件
- 執(zhí)行步驟一、的腳本命令
$ npm run p
-
輸入文件名
!!在配置的路徑下生成對應(yīng)的文件
-
生成文件即是模版的內(nèi)容
大功告成??????