安装
yarn add plop --dev
项目根目录创建plopfile.js 文件,定义脚手架的任务
// Plop 入口文件 需要导出一个函数
// 此函数接收一个 plop 对象, 用于创建生成器的任务
module.exports = plop => {
plop.setGenerator('component', {
description: 'create a component', // 描述
prompts: [ // 指定generator工作的时候发出的命令行问题
{
type: 'input', // 输入方式
name: 'name', // 返回值的健
message: 'component name', // 提示
default: 'MyComponent' // 默认答案
}
],
actions: [ // 生成器完成命令行交互之后需要执行的动作, 每个对象就是动作对象
{
type: 'add', // 添加一个全新的文件
path: 'src/components/{{name}}/{{name}}.js', // 被添加到的具体的路径, name就是 prompts 的name取值
templateFile: 'plop-templates/component.hbs' // 本次添加文件的模版文件
},
{
type: 'add',
path: 'src/components/{{name}}/{{name}}.css',
templateFile: 'plop-templates/component.css.hbs'
}
]
})
}
项目根目录创建模版文件
plop-templates/component.hbs
plop-templates/component.css.hbs
component.hbs文件
import React from 'react';
class {{name}} extends React.Component{
render(){
return(
<h1 className="{{name}}">{{name}}</h1>
)
}
}
export default {{name}}
component.css.hbs文件
.{{name}} {
}
终端命令行输入
yarn plop component
image.png
回车之后会根据你设置的问题进行询问,不输入就是默认答案
image.png
创建成功的文件
image.png
总结
- 将plop模块作为项目的开发依赖安装
- 在项目的根目录新建plopfile.js文件
- 在plopfile.js文件定义脚手架任务
- 编写用于生成特定类型文件的模板
- 通过plop提供的CLI 运行脚手架任务