Yeoman:
-
过于通用,不够专注
-
搭配特定的Generator可以创建自己的脚手架
简单使用
-
在全局范围安装yo
npm install yo --global 或 yarn global add yo
-
安装对应的generator:
npm install generator-node --global 或 yarn global add generator-node
-
通过yo 运行 generator
yo node
Sub Generator:
子集生成器,需要先确认用到的Generator 是否有子集生成器
-
使用:
yo node:cli
yeoman使用步骤:
- 明确需求
- 找到合适的Generator
- 全局范围安装找到的Generator
- 通过Yo运行对应的Generator
- 通过命令行交互填写选项
- 生成所需要的项目结构
自定义Generator模块:
本质是一个NPM模块
基于Yeoman 搭建自己的脚手架
Generator基本结构
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-0SPbvrga-1621064634583)(C:/Users/86150/AppData/Roaming/Typora/typora-user-images/image-20210513115019634.png)]
Generator模块名称
generator-
自定义脚手架基本构建过程:
-
创建目录 generator-sample
-
创建package.json
yarn init
-
安装生成器基类 yeoman-generator
-
创建目录结构 generators/app/index.js 的Generator核心入口文件
-
模块链接到全局范围
yarn link
根据模板创建文件:
写入多个文件时比较方便,一两个就。。。
writing( )
创建目录结构 generators/app/templates/foo.txt
foo.txt
模板方式
EJS模板标记输出数据
<%= title %>
其他EJS使用方式
<% if (success) { %>
happy
<% } %>
模板文件路径:
const tmpl = this.templatePath('foo.txt')
输出目标路径:
// const output = this.destinationPath('foo.txt')
模板数据上下文:
const context = { title: 'Hello zce~', success: true}
模板文件映射到输出文件:
this.fs.copyTpl(tmpl, output, context)
接收用户输入:
prompting( )
在此方法中可以调用父类的 prompt() 方法发出对用户的命令行询问
index.js
prompting(){
return this.prompt([
//命令行询问信息
{
type: 'input',
name: 'name',
message: 'Your project name',
default: this.appname
}
])
.then(answers => {
this.answers = answers
})
}
writing(){
// 模板文件路径
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>
<h3><%= name %></h3>
</body>
</html>
发布Generator模块
- 创建.gitignore 并忽略node_modules
echo node_modules > .gitignore
-
将本地仓库推送到远程仓库
-
发布命令,在国内因为淘宝镜像源(只读)不易发布到npm中
一定注意:npm 注册后要验证邮箱,发布好几次失败是因为邮箱未验证没有权限发布
yarn publish --registry=https://registry.yarnpkg.com
les
echo node_modules > .gitignore
-
将本地仓库推送到远程仓库
-
发布命令,在国内因为淘宝镜像源(只读)不易发布到npm中
一定注意:npm 注册后要验证邮箱,发布好几次失败是因为邮箱未验证没有权限发布
yarn publish --registry=https://registry.yarnpkg.com