介绍
主要用于创建特定类型文件的小工具,有点类似于yeoman中的sub-generator,一般不独立使用,用于集成到项目当中,创建一些同类型的项目文件
实例
在react项目中创建组件时,往往需要创建3个文件
现在在react项目安装plop
yarn add plop --dev
安装完成之后,在根目录创建plopfile.js的文件,是入口文件
在根目录创建模版目录plop-templates,在其中添加模版.hbs模版引擎类型文件,可以通过{{ }}语法插入相应的数据
setGenerator,第一参数为模版名称 description描述
// Plop 入口文件,需要导出一个函数
// 此函数接收一个 plop 对象,用于创建生成器任务
module.exports = plop => {
plop.setGenerator('component', {
description: 'create a component',
prompts: [
{
type: 'input',
name: 'name',
message: 'component name',
default: 'MyComponent'
}
],
actions: [
{
type: 'add', // 代表添加文件
path: 'src/components/{{name}}/{{name}}.js',
templateFile: 'plop-templates/component.hbs'
},
{
type: 'add', // 代表添加文件
path: 'src/components/{{name}}/{{name}}.css',
templateFile: 'plop-templates/component.css.hbs'
},
{
type: 'add', // 代表添加文件
path: 'src/components/{{name}}/{{name}}.test.js',
templateFile: 'plop-templates/component.test.hbs'
}
]
})
}
总结
- 将polp模块作为 项目开发依赖安装
- 在项目根目录下创建一个plopfile.js文件
- 在plopfile文件中定义脚手架任务
- 编写用于生成特定类型生成的模版
- 通过plop提供的cli运行脚手架任务