(安装直接官网)

第一件事情就是使用 npm 来安装 yo :

npm install -g yo
然后安装需要的 generator(s)。 Generators 是一个名字为 generator-XYZ 的 npm 包。
你可以在 我们的网站找到它们或者使用 "install a generator" 按钮选项来选择,然后去跑 yo。 去安装这个 webapp generator:
npm install -g generator-webapp

使用:命名一个generator-(这里写自己生成器的名字)文件夹
  安装yeoman-generator
  文件夹中建立一个名为generator的文件夹再在其中建立app文件夹
  app中写index.js文件
  文件中写(文件结构默认就是固定的,package.json在generator-(xxx)中)

const Generator = require('yeoman-generator')

module.exports= class extends Generator{
    writing(){
        this.fs.write(this.destinationPath('test.txt'),
        Math.random().toString())
    }
}

切回generator-(xxxx)的上层目录执行yo-(自己生成器的名字)
这样就会在根目录下用生成器生成一个test.txt这个文件
  • 使用模板和命令行交互

在app中建立templates文件夹

yeoman中支持ejs模板语法

修改上代码

const Generator = require('yeoman-generator')

module.exports= class extends Generator{
     prompting(){
         //这里加了return后才不会报错
        return this.prompt([
            {
                type:'input',
                name:'title',
                message:'Ydjdjddjdj',
                default:this.appname
            }
        ]).then(answers=>{
            console.log(answers)
            this.answers=answers
        })
    }
    writing(){
        // this.fs.write(this.destinationPath('test.txt'),
        // Math.random().toString())
        const temp = this.templatePath('index.html') //读取模板
        const output = this.destinationPath('index.html') //根据模板生成文件
        const context= this.answers  //替换内容
        this.fs.copyTpl(temp,output,context)  //执行替换

    }
}

这里就可以生成一个交互的后的模板文件

如果要搭建一个yeomen下的vue可以先将vue脚手架中的文件拷贝到模板文件夹中然后通过遍历的方式将文件输出,yeomen会自动生安装依赖

 

posted on 2021-11-04 11:05  ygdong  阅读(53)  评论(0)    收藏  举报