Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

PS: Generator-VUUE -3 (create vue3+ TS + ESLint project) : github address, NPM address

preface

Speaking of scaffolding, you should be familiar with. We are familiar with create-react-app for creating react stack projects and vuE-CLI for creating VUE stack projects, both of which help us to quickly build project scaffolding from 0 to 1.

So why would we want to build our own scaffolding when we already have mature scaffolding?

Typically, a team project will have some custom configurations:

  1. Ci scripts published by the project
  2. Eslint and other specification configurations
  3. Env Configuration of different environments
  4. Login Proxy Configuration

.

If you reconfigure each new project, or make a copy of the original project and change it. That can not guarantee the consistency of everyone’s project technology stack, but also affect everyone’s development efficiency. Could we write our own template and create custom projects automatically like vue-CLI scaffolding?

Today I’m going to share with you how to customize your own project scaffolding to improve development efficiency.

What is a yeoman

Yeoman’s official website

Introduction to the

Yeoman is a scaffolding tool for modern front-end projects, used to generate engineered directory structures containing specified framework structures. It is the first stop in the entire front end automation factory.

Yeoman is a scaffold execution framework that defines the stages a scaffold goes through (reading user input, generating project files, and installing dependencies), all we need to do is fill in the corresponding operation codes at the corresponding stages of the lifecycle.

The life cycle

Yeoman provides a life cycle for each phase, with the following priorities in order of run:

  1. initializing– Initialization phase (check current project status, get configuration, etc.)
  2. prompting– User input phase (Where you’d callthis.prompt())
  3. configuring– Save the configuration and configure the project (create.editorconfigFiles and other metadata files)
  4. default– Default execution phase
  5. writing– Write new project structures based on templates (routing, console, etc.)
  6. conflicts– Handling conflict phase (internal use)
  7. install– Installation dependency phase (NPM, Bower)
  8. end– Closing phase (cleaning up redundant files, etc.)

By following these priorities, your generator will coexist nicely with others.

To understand theyeomanNext, let’s take a look at how Yeoman generates scaffolding.

What is the generator

The generator – XXX generator

Yeoman is a scaffold running framework, and projects that want to generate a scaffold template need to find the corresponding generator named generator-xxx. Yeoman can generate a scaffold project by calling generator-xxx with the yo command.

Which means you need to passyeomancallgeneratorTo generate project scaffolding, all need to be namedgenerator-xxx(xxxFor scaffold name, passyo xxxMake a call)

generator-generator

Yeoman provides a generator-generator to help you quickly generate a scaffold template.

How do I generate scaffold templates

Install Yeoman and Generator

Global installation yo(Yeoman) and Generator-Generator (generate scaffold templates)

npm install yo generator-generator -g
Copy the code

Generate scaffold templates

yo generator
Copy the code

To execute the above command, as shown below, enter yourgenerator-name, can be published through the callyo nameCommand to generate the project for this scaffold.

After execution, scaffold template projects are generated as follows:

.├ ─ └─ ├─ index.js // / ├─ ├─ index.js // // // // // // // // // // Can be after their configuration project │ └ ─ ─ dummyfile. TXT ├ ─ ─ the editorconfig ├ ─ ─ the eslintignore ├ ─ ─ the gitattributes ├ ─ ─ the gitignore ├ ─ ─. Travis. Yml ├ ─ ─. Yukio okamoto, - rc. Json ├ ─ ─ LICENSE ├ ─ ─ the README. Md ├ ─ ─ package. The json └ ─ ─ __tests__ / / / test cases └ ─ ─ app. JsCopy the code

How to customize scaffolding

Template template

Template template directory: / generators/app/templates

Template files or template projects can be placed in this folder, and fields in the template files or template projects can be rewritten or replaced by life cycle stages in app/index.js to generate new projects.

Templates in the figure below shows the customized VUE template project The red box in package.json is the content to be filled after waiting for user input

The configuration file

Configuration file directory: /generators/app/index.js

The Yeoman-Generator base library is provided on which you can extend and populate.

index.js

"use strict";
const Generator = require("yeoman-generator");
const chalk = require("chalk");
const yosay = require("yosay");
const path = require("path");
const mkdirp = require("mkdirp"); // 5.0.0 requires install const _ = require("lodash");
_.extend(Generator.prototype, require("yeoman-generator/lib/actions/install")); Module.exports = class extends Generator {// Show the user the key parameters of interactive problem collectionprompting() {
    // Have Yeoman greet the user.
    this.log(
      yosay(
        `Welcome to the stunning ${chalk.red("generator-vue-3")}generator! `)); const prompts = [ {type: "input",
        name: "namespace",
        message: "Please input your project namespace,such as @baidu:",
        default: ""
      },
      {
        type: "input",
        name: "name",
        message: "Please input project name:",
        default: "vue"
      },
      {
        type: "input",
        name: "description",
        message: "Please input project description:",
        default: "a vue project"
      },
      {
        type: "input",
        name: "author",
        message: "Author's Name",
        default: ""
      },
      {
        type: "input",
        name: "email",
        message: "Author's Email",
        default: ""
      },
      {
        type: "input",
        name: "license",
        message: "License",
        default: ""}];return this.prompt(prompts).then(props => {
      // To access props later use this.props.someAnswer;
      this.props = props;
      if (this.props.namespace) {
        this.props.fullName = this.props.namespace + "/" + this.props.name;
      } else{ this.props.fullName = this.props.name; }}); } // Non-private methods that do not match any lifecycle methods are executed * automatically * in this segmentdefault() {
    if(path.basename(this.destinationPath()) ! == this.props.name) { this.log(`\nYour generator must be inside a folder named${this.props.name}\n I will automatically create this folder.\n`); mkdirp(this.props.name); this.destinationRoot(this.destinationPath(this.props.name)); }} // Write the new project structure according to the templatewriting() {
    this.log("\nWriting... \n");

    this.__writingCopy(["package.json"], {
      name: this.props.name,
      fullName: this.props.fullName,
      description: this.props.description,
      author: this.props.author,
      email: this.props.email,
      license: this.props.license
    });
    this.__writingCopy(["README.md"], {
      name: this.props.name,
      fullName: this.props.fullName,
      description: this.props.description,
      author: this.props.author,
      year: new Date().getFullYear()
    });
    this.__writingCopy([
      "build"."public"."src".".browserslistrc".".editorconfig".".env.development".".env.production".".env.test".".eslintrc.js".".eslintrc.json".".gitignore"."babel.config.js"."ci.yml"."stylelint.config.js"."tsconfig.json"."vue.config.js"
    ]);
  }

  __writingCopy(filePath, params) {
    this.log(this, "haha"); filePath.forEach(item => { this.fs.copyTpl( this.templatePath(item), this.destinationPath(item), params ); }); } // Install dependency phaseinstall() {
    this.log("install..."); // This.npminstall () is disabled by default; }};Copy the code

Not automatic after 5.0.0installRely on

Yeoman-generator5.0.0 does not automatically install dependencies. You need to manually trigger the dependencies in the following ways:

After configuring the template files and configuration files, the scaffolding is complete, and we are ready to test the scaffolding.

How to test scaffolding

The NPM link module links to the global

You can use the module globally by linking it to global node_modules via NPM link.

callyo xxxGenerate scaffold project

The locally developed generator-xxx has not been published. You need to open the command line in the package.json directory, enter NPM link to install it to the local global environment, and then call it in yo XXX or Yo XXX: YYY mode. The result is as follows:

Enter the scope, name, description and other information of the project as prompted. The project will be automatically generated. After entering the generated project, if there is no install dependency, you need to manually install the dependency and run it again.

throughNPM Link, Yo XXXTo test whether the scaffolding project can be generated smoothly.

If # NPM ERR! Error: Notarget No matching version found for @babel/[email protected] NPM cache clean –force

How to Publish scaffolding

Distribute the locally developed generator-xxx scaffolding as an NPM package. Release steps are as follows:

  1. Login NPM:npm login
  2. Publish NPM:npm publish

Published successfully, as shown below:

Check out the package generator-VUE-3 just released on NPM:

How to Use scaffolding

Globally install scaffolding, such as generator-VUE-3

npm install -g generator-vue-3
Copy the code

Use yo to call the scaffold build project

yo vue-3
Copy the code

After the build is successful, go to the directory and start the project.

Refer to the article

  1. Juejin. Cn/post / 684490…
  2. zhuanlan.zhihu.com/p/66190308
  3. zhuanlan.zhihu.com/p/51704240
  4. Yeoman. Making. IO/generator/I…
  5. Juejin. Cn/post / 684490…