创建一个生成器 generato

//创建一个生成器

 创建文件

mkdir generator-sample

cd  ./generator-sample

yarn init  --初始化package.json文件

yarn add yeoman-generator  --添加一个yeoman-generator生成器的基类, 提供了一些工具函数,创建生成器更加便捷

在根目录创建文件夹和文件

generators/app/index.js    必须这个结构

创建模板文件

generators/app/tmplates/bar.html

bar.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title><%= name %></title>
</head>
<body>
  <h1><%= name %></h1>
</body>
</html>

index.js

//此文件作为Generator的核心入口
//需要导出一个继承自 yeoman generator 的类型
//yeoman generator 在工作的时候会自动调用我们在此类型中定义的一些生命周期方法
//我们在这些方法中可以通过调用父类提供的一些工具方法实现一些功能,泪如文件写入

const Generator = require('yeoman-generator')

module.exports = class extends Generator {

    prompting() {
        return this.prompt([{
            type: "input",
            name: "name",
            message: "Your project name",
            default: this.appname
        }]).then( answers => {
            //answers = {name: "You APP name"}
            this.answers = answers
        })
    }

    writing () {
        //yeoman 自动在生成阶段会调用此方法
        //我们这里尝试在项目目录中写入文件

        // this.fs.write(
        //     this.destinationPath('temp.text'),
        //     Math.random().toString()
        // )
        //通过模板方式写入文件到目标目录
        const tmpl = this.templatePath("bar.html")
        //输出目标路径
        const output = this.destinationPath('bar.html')
        //模板数据上下本
        // const context = {title: "hello", success: true}
        const context = this.answers

        this.fs.copyTpl(tmpl, output, context)
    }
}

yarn link 发布项目

退出项目  创建一个新文件

mkdir my-project

运行

yo  sample   //生成   bar.html  <%=  name %>  被替换

原文地址:https://www.cnblogs.com/faint33/p/14718048.html