创建Generator 模块
Generator 本质上就是一个NPM模块,但是Generator 有一个特定结构
首先我们创建一个文件夹当做目录
# mkdir generator-sample
# yarn init
# yarn add yeoman-generator
# code . //打开VScode
然后我们按照按照上面的基础结构创建相应的文件夹
在index js 中可以直接创建
consst Generator =require('yeoman-generator')
module.exports = class extends Generator{
writing(){
//yeoman 自动在生成文件阶段调用此方法
// 我们这里尝试往项目目录中写入文件
this.fs.writing(
this.dedtinationPath('temp.txt'),
Math.random().toString()
)
}
}
//命令行
# yarn link
# yo sample //文件名
## 根据模板创建文件
```javascript
consst Generator =require('yeoman-generator')
module.exports = class extends Generator{
writing(){
//yeoman 自动在生成文件阶段调用此方法
// 我们这里尝试往项目目录中写入文件
//this.fs.writing(
// this.dedtinationPath('temp.txt'),
// Math.random().toString()
//)
//通过末班方式写入文件到到目标目录
const tmpl=this.templatePath('foo.txt')
//输出目标路径
const output = this.destinationPath('foo.txt')
//模板数据上下文
const context={title:'Hello dzj-',sucess:false}
this.fs.copyTpl(tmpl,output,context )
}
}
相对于手动去创建每一个文件,模块的方式大大提高了效率
接受用户输入------prompting()
consst Generator =require('yeoman-generator')
module.exports = class extends Generator{
paompting(){
// yeoman 在询问用户环节会自动调用此方法
// 在此方法中可以调用父类的 prompt() 方法 发出对用户的命令行询问
return this.prompt([
{
type:'input',
name:'name',
message:'your Project name',
default:this.appname ,//appname 为项目中生成目录名称
}
])
。then(answers=>{
// answers =>{ name :' user input name'}
this.answers=answers
})
}
writing(){
//yeoman 自动在生成文件阶段调用此方法
// 我们这里尝试往项目目录中写入文件
//this.fs.writing(
// this.dedtinationPath('temp.txt'),
// Math.random().toString()
//)
//通过末班方式写入文件到到目标目录
const tmpl=this.templatePath('foo.html')
//输出目标路径
const output = this.destinationPath('bar.html')
//模板数据上下文
const context=this.answers
this.fs.copyTpl(tmpl,output,context )
}
}
yo sample //名称
以上内容均为个人学习笔记,不存在任何其他或者商业行为 ,如有侵权或者其他,必删除。请私聊或者评论告知。