Yeoman 的简介
基于node 开发的一个工具模块, 创建通用型脚手架
Yeoman 的基础使用
- 在全局范围安装 yo
npm install yo --global # or yarn global add yo
- 安装对应的generator
npm install generator-node --global # or yarn global add generato-node
- 通过 yo 运行 generator
mkdir my-module
cd my-module
yo node
完成之后即得到项目结构
sub generator
生成器
yeoman 使用步骤
- 明确你的需求
- 找到合适的 Generator
- 全局范围安装找到的 Generator
- 通过 yo 运行对象的 Generator
- 通过命令行交互填写选项
- 生成你所需要的项目结构
自定义 Generator
基于 yeoman 搭建自己的脚手架
创建 Generator
Generator 用例及与用户自定义操作
- prompting 与用户进行操作
- writing 写入文件
操作文件
/*
* @Descritption:
* @Author: wangzhenyu
* @Date: 2021-09-01 14:02:45
* @LastEditors: wangzhenyu
* @LastEditTime: 2021-09-01 16:34:22
*/
// 此文件为 Generator 的核心入口
// 需要导出一个继承自 Yeoman Generator 的类型
// Yeoman Generator 在工作时会自动调用我们在此类型中定义的一些生命周期方法
// 我们在这些方法中可以通过调用父类提供的一些工具方法去实现一些功能,比如文件使用
const Generator = require('yeoman-generator')
module.exports = class extends Generator{
prompting(){
// Yeoman 在询问用户环节会自动调用此方法
// 在此方法中可以调用父类的 prompt() 方法发出对用户的命令行询问
return this.prompt([
{
type: 'input',
name: 'name',
message: 'your project name',
default: this.appname // appname 为项目生产目录名称
}
]).then(answers => {
// answers => {name: 'user input value}
this.answers = answers
console.log(answers)
})
}
writing(){
// Yeoman 自动在生成文件阶段调用此方法
// 我们尝试往项目目录中写入文件
// this.fs.write(
// this.destinationPath('temp.txt'),Math.random().toString()
// )
// 通过模板方式写入文件到目标目录
// // 模板文件路径
// const tmpl = this.templatePath('foo.txt')
// // 输出目标路径
// const output = this.destinationPath('foo.txt')
// // 模板数据上下文
// const context = {title: 'hello zce-', success: false}
// this.fs.copyTpl(tmpl, output, context)
// 模板文件路径
const tmpl = this.templatePath('bar.html')
// 输出目标路径
const output = this.destinationPath('bar.html')
// 模板数据上下文
const context = this.answers
this.fs.copyTpl(tmpl, output, context)
}
}
模板文件
<%= %> 中间填写变量
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><%= name %></title>
</head>
<body>
</body>
</html>