全局安裝 yeoman-generator
yarn global add yeoman-generator
创建 generator-sample-vue
mkdir generator-sample-vue
cd generator-sample-vue
安装yeoman-generator
yarn add yeoman-generator
新建目录结构
在使用yo 时,会自动调用index.js中的代码
// index.js 文件
// this file is the main entry of Generator
// 这个文件是 Generator 的主入口
// export a type which extends Yeoman Generator class
// 这里会导出一个继承自Yeoman Generator 的 class
// Yeoman Generator invoke some life cycle funcs in our class when Yo are working
// 当 Yeoman Generator 运行时,会调用我们自定义class中的一些方法
// we can use some funcs of parent class, ex: write file
// 在我们的class中可以使用一些父类中的方法来实现功能
const Generator = require('yeoman-generator')
const path = require('path');
module.exports = class extends Generator{
prompting(){
return this.prompt([
{
type: 'input',
name: 'name',
message: 'Your project name',
default: this.appname // 当前目录文件夹的名字
}
])
.then(answers => {
console.log('sanswers', answers)
this.answers = answers
})
}
async writing(){
const templates = [
'.env.dev.serve',
'.env.production.serve',
'.env.test.serve',
'.gitignore'
]
// 这个循环的操作,是因为使用copyTplAsync方法,默认忽略‘.’开头的隐藏文件,所以需要手动点名字,一个一个复制过去
templates.forEach(item => {
this.fs.copyTpl(
this.templatePath(item),
this.destinationPath(item),
this.answers
)
})
// this.fs.copy('package.json', 'package.json');
// 因为程序员天生的惰性不想,一个目录一个文件的去生成templates,所以用下面这个方法,全部copy
await this.fs.copyTplAsync(path.join(__dirname, '/templates/'), './', this.answers);
}
}
注意啦!!!
如下图中标记,需要直接输出ejs语法,不需要替换,所以加一个%
自定义generator时,必须使用格式generator-[[name]] 举例:generator-example
开发时,使用yarn link本地调试
本地使用时,新建myproject 文件夹,运行如下:
yo example