写在前面
笔记内容大多出自于拉勾教育大前端高薪训练营的教程,因此也许会和其他文章雷同较多,请担待。
Yeoman
$ npm i yo -g / $ yarn global add yo
$ npm i generator-node -g / $ yarn global add generator-node // 基于node的开发脚手架,具体开发脚手架可以去https://yeoman.io/generators/查询
$ mkdir my-module
$ yo node
// tip about Sub Generator
$ yo node:boilerplate
$ yo node:cli // 通过node:cli创建一个cli应用
$ yo node:editorconfig
$ yo node:eslint // 通过node:eslint创建eslint规范
$ yo node:git // 通过node:git创建git仓库
$ yo node:readme // 通过node:readme创建readme文档
$ yo node:xxx --help // 查询node:xxx相关配置
$ yarn link // 注册该项目到全局范围,其他项目如果想要使用到这个项目的内容只需要require就可以,比如project_A想要使用project_B,先进入project_B的cmd输入yarn link,然后进入project_A的cmd输入yarn link project_B,然后require('project_B')就可以了。project_B所做的修改也能及时反应到project_A上
自定义Generator
$ mkdir generator-sample
$ cd generator-sample\
$ yarn init
$ yarn add yeoman-generator // 提供生成器的基类,内含一些工具函数,可以让创建生成器时更加便捷
$ md generators/app/index.js // 此文件作为Generator的核心入口,需要导出一个继承自yeoman-generator的类型,这样在运行时程序会自动调用我们自己创建的generator里面的生命周期方法,我们可以在这些方法中调用父类提供的一些工具方法实现一些功能,比如文件写入
const Generator = require('yeoman-generator')
module.exports = class extends Generator {
prompting() {
// yeoman在创建脚手架时都会调用此方法对用户进行配置提问
this.prompt([
{
type: 'input',
name: 'name',
message: 'set html title',
default: this.appname // 如果没设置则使用项目名
},
{
type: 'input',
name: 'success',
message: 'sayHello?',
default: false // 如果没设置则使用项目名
}
])
.then(answers => {
this.answers = answers // { name: 'aeorus', success: true } 两个提问,第一个输入了aeorus,第二个输入了true
})
}
writing() {
// 尝试往项目中写入一个名为test.txt的文件,内容是个随机数
this.fs.write(
this.destinationPath('test.txt'), // destinationPath(filepath: string) 类似于node的path方法里面的resolve,寻找当前目录下的文件
Math.random().toString()
) // write(filepath: string, contents: string): void
}
render() {
// 尝试往项目中写入一个名为tpl.txt的文件,内容是一个已渲染的模板
// 模板文件路径
const tpl = this.templatePath('tpl_this.txt') // this.templatePath(filepath: string) 寻找templates目录下的文件
// 输出目标路径
const output = this.destinationPath('tpl_that.txt')
// 模板数据上下文
const context = this.answers
this.fs.copyTpl(tpl, output, context)
}
}
/*
// templates/tpl_this.txt
我的名字是<%= name %>
<% if (success) { %>
你好
<% } %>
*/
$ yarn link // 注册到全局范围
$ mkdir test-app // 创建一个名为test-app的新项目
$ yo sample // sample是上面创建的自定义的generator的名字
- create test.txt // test-app里面自动创建一个名为test.txt的文件,内容是个随机数
- create tpl_that.txt // test-app里面自动创建一个名为tpl_that.txt的文件,内容是“我的名字是aeorus,你好”
Plop -> 可以用来创建需要被重复创建的文件
$ yarn add plop --dev
$ md 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' // plop-templates/component.hbs
}
]
})
}
yarn plop component