开门见山
在前端工具-自定义generator文章中,介绍了如何自定义generator模块,以及生成对应的文件,如果是一个接一个写文件的话
比较费力,好在我们有模板语法通过模板语法,大大提高了效率
模板语法
const Generator = require('yeoman-generator');
module.exports = class extends Generator {
//通过模板的方式写入文件到目标目录 模板内部自动使用EJS语法
//模板路径
const templ = this.templatePath('foo.txt');
//输出目标路径
const output = this.destinationPath('foo.txt');
//文件内容
const content = {title:"hello world",success:"success"}
//运行 自动把模板文件映射到输出文件上
this.fs.copyTpl(templ,output,consent)
}
接收用户输出
不知道大家有没有印象,在vue使用过程中,有需要输入项目名称,那么是怎么做到的呢,其实就是接收用户输入信息而已
为大家演示一下
//只需要实现prompt方法即可,
const Generator = require('yeoman-generator');
module.exports = class extends Generator {
prompting(){
return this.prompt([{ //可以
type: "input", //输出
name: "name", //key值 name其实就是洗面answer的name
message: "Your project name", //提问信息
default: this.appname //默认名字
}]).then(answer => { //支持链式调用
//answer => { name :"user input value" } 并且挂载到this以便于更好地调用
this.answer = answer
})
}
//通过模板的方式写入文件到目标目录 模板内部自动使用EJS语法
//模板路径
const templ = this.templatePath('foo.txt');
//输出目标路径
const output = this.destinationPath('foo.txt');
//文件内容
const content = this.answer //在这里将content替换成this.answer
//运行 自动把模板文件映射到输出文件上
this.fs.copyTpl(templ,output,consent)
}
谢谢观看,如有不足,敬请指教