小而美的脚手架工具
主要用于去创建项目中特定类型的文件的小工具,有点像Yeoman 中的Sub Generator,不过plop不会独立使用,
一般我们都会把plop集成到项目中用来创建同类型的项目文件。
plop基本使用
-
将plop模块作为项目开发依赖安装
yarn add plop --dev
在项目根目录下创建一个plopfile.js文件
-
在plopfile.js文件中定义脚手架任务
// plopfile.js // 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}}.less', templateFile: 'plop-templates/component.less.hbs' }, { type: 'add', //表示添加文件 path: 'src/components/{{name}}/{{name}}.test.js', templateFile: 'plop-templates/component.test.hbs' } ] }) }
-
编译用于生成特定类型文件的模板
在根目录创建plop-templates用于存放各种模板
模板文件使用了模板引擎-hbs (Handlebars)
component.hbs
import React from 'react'; export default () => { <div className="{{name}}"> <h1>{{name}} Component</h1> </div> }
component.less.hbs
.{{name}}{ }
component.test.hbs
import React from 'react'; import ReactDOM from 'react-dom'; import {{name}} from './{{name}}' it ('renders without crashing',() => { const div = document.createElement('div'); ReactDOM.render(<{{name}}/>,div); ReactDOM.unmountComponentAtNode(div); })
-
通过plop提供的CLI运行脚手架任务
yarn plop component