分类
- Vue-cil、create-react-APP:对应框架的脚手架
- Yeoman:创建项目,比较通用
- plop:小型,在项目组创建特定类型文件
工作过程
- 通过命令行交互询问用户问题
- 根据用户回答结果生成文件
Yeoman
- 安装
yarn global add yo
yarn global add generator-node
yo node
- Sub-generator 在原有项目添加配置文件
// 安装特定生成器
yo node:cli
// link到全局范围
yarn link
-
使用总结
- 明确你的需求;
- 找到合适的Generator;
- 全局范围安装找到的Generator;
- 通过Yo运行对应的Generator;
- 通过命令行交互填写选项;
- 生成你所需要的项目结构;
-
自定义generator
- 本质上就是一个npm模块
- 创建: mkdir generator-demo cd ./generator-demo
- 安装: yarn init yarn add yeoman-generator
- 创建目录结构: mkdir generators/app cd ./app touch index.js
- index.js
const Generator = require('yeoman-generator'); module.exports = class extends Generator { // 处理用户输入 prompting(){ return this.prompt([ { type: 'input', name: 'name', message: 'msg', default: this.appname //appname是项目生成的目录名 } ]).then(answers => { this.answers = answers }) } writing(){ // 1.直接写入 this.fs.write( this.destinationPath('demo.txt'), // 要写入的内容 Math.random().toString() ) // 2.模板写入 // const tmpl = this.templatePath('foo.txt') // const output = this.destinationPath('foo.txt') // const context = this.answers // this.fs.copyTpl(tmpl, output, context) } }- 回到generator-demo目录执行:yarn link
- 生成写入的文件:yo demo
-
发布generator
- 创建git仓库
- 提交代码
- yarn publish
plop
- 可以在重复创建相同类型的文件时使用
- 安装:yarn add plop --dev
- 创建文件:plopfile.js
module.exports = plop => {
plop.setGenerator('component', {
description: 'create a component',
prompts: [
{
type: 'input',
name: 'name',
message: 'msg',
default: 'my'
}
],
actions: [
{
type: 'add',
path: 'src/component/{{name}}/{{name}}.js',
templateFile: 'tem/component.hbs'
}
]
})
}
- 创建模板:tem/component.hbs
import React from "react";
export default () => (
<div className="{{name}}">
{{name}}
</div>
)
- 运行:yarn plop component
自定义脚手架
- 根据用户在命令行回答的问题,结合模板文件创建项目结构
- 创建新目录,执行yarn init
- 修改package.json,添加配置:"bin": "cli.js"
- 创建文件cli.js,写入测试代码
- 执行 chmod 755 cli.js yarn link demo
- 安装询问模块:yarn add inquirer
- 修改cli.js
const inquirer = require('inquirer') inquirer.prompt([ { type: 'input', name: 'name', message: 'Project' } ]) .then(answers => { console.log('answers', answers); }) - 创建模板目录,读取模板
- 安装模板引擎:yarn add ejs