Use Yeoman to implement your own scaffolding tool

Introduction and Demo

yeoman is a general-purpose scaffolding that can be used to define your own scaffolding tools

Core principle:

yo + different generators = different projects

Quickly use a generator to build projects

Note: Let's take generating an eslint plugin development template as an example! ! ! ! ! ! ! ! ! ! ! !

First, you need to confirm the environment (must have a node environment)

node -v
npm -v

Change the mirror source to a domestic mirror (to ensure faster download speed of dependencies)

npm config set registry https://registry.npmmirror.com

tip: You can view the mirror source through npm config get registry *

Install the yo command globally

npm i yo -g

Install the corresponding generator generator globally

npm i generator-eslint -g

The format of the generator is generator-name

Create a project and enter the directory

mkdir yeoman-eslint
cd yeoman-eslint

Run the corresponding generator through yo

yo eslint

The generator can be omitted when using-

Customize a generator mystudy

Project build

1. The generator itself is also a project, which needs to be created

mkdir generator-mystudy
cd generator-mystudy
npm init -y

Note: The project name of the generator must start with generator-

2. Install the base class in the project

npm i yeoman-generator -S

There are many methods encapsulated in this plug-in, we will use this plug-in when we develop it later.

3. Edit the entry file

generator-mystudy/generators/app/index.js

Since we can create multiple generators, the file is named generators

Don't worry about why the entry file is created in this way, this is the official specification, and we will explain it in detail later. Let's experience the process first.

Develop mystudy generator

Before learning the following content, please strengthen the study of js class first! !

Simply write a line of code in the entry file

// 引入生成器的父类
const Generator = require("yeoman-generator");
// 导出继承的子类
module.exports = class extends Generator {
  // 子类被new时,test方法会自动执行
  test(){
    // 这里没有使用console.log();方法,而是直接使用了父类封装的log方法,因为console在某些情况可能出错
    this.log("我的第一");
  }
};

Now, a simple generator is completed. In theory, we can directly use npm i generator-mystudy -g locally . However, we first need to make the generator-mystudy directory accessible to npm globally.

View the root directory of the npm global installation

npm root -g

In order to observe whether our directory is set as a global directory, we can first open the npm root directory

open this folder in window

start D:\Program\node\node_modules

Link the project to the npm root (global access to the project)

npm link

After executing the command, you can find that the shortcut in the directory has been created, and now you can access the project globally.

try our generator

yo mystudy

tip: generator- can be omitted

Now, open the console and see that the contents of the generator are printed. Our generator is already running normally, check it out!

Improve the mystudy generator

Ideas:

  1. ask, get information
  2. Generate a predefined project structure
  3. install dependencies

First of all, we need to understand the Generator's construction method, query, rendering template and installation dependencies and other functions.

For the following function names, etc., we have adopted the official api. This article focuses on experience. You can learn about the specific usage in the next article.

User interaction

User interaction is done through the prompting method, which is an official api

The interactive process here refers to the content of requirejs, so we can refer to requireJs for specific usage methods

// 引入生成器的父类
const Generator = require("yeoman-generator");
// 导出继承的子类
module.exports = class extends Generator {
  // 构造方法可以处理自定义的命令行参数
  constructor(args, opts) {
    super(args, opts);
  }
  // 1.询问,获取信息
  prompting() {
    // prompt方法返回一个promise,用于询问用户信息,并返回一个结果对象
    return this.prompt([
      {
        // 问题类型,需要用户输入
        type: "input",
        // 信息储存的字段
        name: "projectName",
        // 提示信息
        message: "请输入项目名称:",
        // 默认值 this.appname默认是项目的文件名
        default: this.appname,
      },
      {
        type: "input",
        name: "username",
        message: "请输入您的名称:",
        default: "",
      },
    ]).then((answers) => {
      this.log(answers);
    });
  }
  // 2.生成预定义的项目结构
  // 3.安装依赖
};

At this point, when we execute yo mystudy on the command line, the query information will be executed, and the information object we need will be returned

Generate project structure

The official writing API is used to generate the directory structure , and methods such as this.sourceRoot() , this.destinationRoot() , and this.fs.copyTpl are used to generate the project structure (generate our project according to the template) .

// 引入生成器的父类
const Generator = require("yeoman-generator");
// 导出继承的子类
module.exports = class extends Generator {
  // 构造方法可以处理自定义的命令行参数
  constructor(args, opts) {
    super(args, opts);
  }
  // 1.询问,获取信息
  prompting() {
    .....
  }
  // 2.生成预定义的项目结构
  writing() {
    // 获取模板目录
    let srcDir = this.sourceRoot();
    // 获取目标目录(在哪里执行命令就是哪里)
    let destDir = this.destinationRoot();
    // 将目标目录内容生成到模板目录内
    this.fs.copyTpl(srcDir, destDir,this.answers);
  }
  // 3.安装依赖
};

install dependencies

If you want to automatically install dependencies when generating the project, just execute the install method.

// 引入生成器的父类
const Generator = require("yeoman-generator");
// 导出继承的子类
module.exports = class extends Generator {
  // 构造方法可以处理自定义的命令行参数
  constructor(args, opts) {
    super(args, opts);
  }
  // 1.询问,获取信息
  prompting() {
    .....
  }
  // 2.生成预定义的项目结构
  writing() {
   ....
  }
  // 3.安装依赖
  install() {
    this.env.options.nodePackageManager = "npm"
    console.log('this.env.options: ', this.env.options);
  }

  end(){
    this.log("项目创建成功")
  }
};

So far, a basic custom generator has taken shape.

Guess you like

Origin blog.csdn.net/weixin_46769087/article/details/128167546