1、创建Generator模块

yeoman的generator名称必须是generator-<name>格式

(1)创建文件夹

mkdir generator-sample

(2)通过yarn init创建package.json

yarn init

(3)创建yeoman-generator模块

yarn add yeoman-generator

(4)打开vscode,在根目录下创建generator/app/index.js

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

const Generator = require('yeoman-generator');
module.exports = class extends Generator {
    writing(){
        // Yeoman自动在生成文件阶段调用此方法
        // 我们这里尝试往项目目录中写入文件
        this.fs.write(
            this.destinationPath('temp.txt'),
            Math.random().toString()
        )
    }
}

 

(5)链接到全局范围,使之成为全局模块包

yarn link

(6)在generator-sample层新建文件夹my-proj,在此文件夹目录下cmd到命令行,运行生成器

yo sample
// 如果成功的话应该是生成一个temp.txt文件,但是我的没有成功,不知道哪一步错了,哼,生气气~

 2、根据模板创建文件

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

const Generator = require('yeoman-generator');
module.exports = class extends Generator {
    writing(){
        // 通过模板方式写入文件到目录
        // 模板文件路径
        const tmpl = this.templatePath('foo.txt');
        // 输出目标路径
        const output = this.destinationPath('foo.txt');
        // 模板数据上下文
        const context = {title:'Hello zce~',success:false};
        this.fs.copyTpl(tmpl,output,context);

    }
}

 

posted on 2021-02-19 20:21  phantom_yy  阅读(107)  评论(0)    收藏  举报