自定义-简单脚手架工具

279 阅读1分钟

需求分析

每次在开发新项目时,总是会有大量重复工作去做,例如:

  • 相同的组织结构
  • 相同的开发范式
  • 相同的模块依赖
  • 相同的工具配置
  • 相同的基础代码

因此考虑去搭建一个可以复用的项目骨架,这里使用,相对较为灵活和容易扩展的yeoman去搭建。

前期准备

yarn global add yo

yo 就是 yeoman 工具模块的名字,而yeoman一般是用不同的generator去生成不同的项目,因此接下来我们自定义一个generator

Generator基本结构

image.png 注:yeoman 的 generator 必须是 generator-生成器名 这样的,不然会找不到

安装 yeoman-generator

image.png

配置书写

/**
 * 这个文件将会作为 generator 的核心入口
 * 需要继承自 yeoman generator 的类型
 * 而 yeoman generaotr 在调用我们定义的生命周期方法
 * 我们也可以用父类的一些方法实现一些功能,比如文件写入等
 */

const Generator = require('yeoman-generator')

module.exports = class extends Generator {
  // 尝试写入文件
  writing() {
    // this.fs.write(
    //   this.destinationPath('temp.txt'),
    //   Math.random().toString()
    // )

    // 模板文件路径
    const tmpl = this.templatePath('foo.txt')
    // 输出文件路径
    const output = this.destinationPath('foo.txt')
    // 上下文数据
    const context = {title: '阿萨德', success: false}

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

此时,通过 yarn-link的方式,link到全局。通过 yo 生成器名,此时就可以创建出一个对应的项目

image.png