1. Scaffolding introduction

1. The essential role of scaffolding

Create project infrastructure and provide project specifications and conventions

Convention:

  • Same organizational structure
  • Same development paradigm
  • Same module dependencies
  • Same tool configuration
  • Same basic code

Give me an example

The PROCESS of creating an IDE project is a scaffolding workflow

For example, when the iOS project uses XCode to create a new project, select the option and click Create, and the project file and directory generated at last is the execution result of a scaffold

Front end scaffolding

  1. The role of scaffolding
  2. Commonly used scaffolding tools
  3. General purpose scaffold tool analysis
  4. Develop a scaffold
Commonly used scaffolding tools
  1. React project -> create-ace -app
  2. Vue project -> Vue – CLI
  3. Angular Project -> Angular-CLI

The corresponding project infrastructure is created based on the information

And then there’s the universal type

  1. Yeoman generates a corresponding project structure from a set of templates
  2. Plop is used to generate specific types of files during project development
    • For example, the files needed to create a component/module

2. The working principle of scaffolding

2. Yeoman, the Generator

Yeoman

The web’s scaffolding tool for modern webapps

1. Basic use of Yeoman

  • Install Yo at the global level
npm install yo --global
# or
yarn global add yo
Copy the code
  • Install the corresponding generator

github.com/yeoman/generator-node

npm install generator-node --global
# or
yarn global add generator-node
Copy the code
  • throughyorungenerator

cd path/to/project-dir

mkdir my-module

yo node
Copy the code

2. Yeoman (Sub Generator)

Subset generator

yo node:cli

To execute the module command, do the following
npm link
[module_name] --help # Check it out
Copy the code

3. General use steps

  1. Identify your needs;
  2. Find the right oneGenerator;
  3. Global scope installation foundGenerator;
  4. throughYoRun the correspondingGenerator;
  5. Fill in options through command line interaction;
  6. Generate the project structure you need;

4. Customize the Generator

Build your own scaffolding based on Yeoman

4.1 Creating a Generator Module

The Generator is essentially an NPM module

  • Basic structure of Generator

The module name must be generator-

# 1. Create
mkdir generator-sample

# 2. To enter
cd generator-sample

# 3. Create an ID card
npm init

# 4. Install yeoman-Generator (base class for generators)
npm i yeoman-generator

Copy the code
// Directory structure
// generators/app/index.js
// In index.js
module.exports = class extends Generator {
  writing() {
    // Yeoman automatically calls this method during file generation
    // We are trying to write files to the project directory
    this.fs.write(
      this.destinationPath('temp.txt'),
      Math.random().toString()
    )
  }
}
Copy the code
  • Link the module globallynpm link
  • Enter the new directory (new project created by scaffolding) to executeyo sample

4.2 Creating a File Using a Template

Templates folder Templates

// Create the templates folder
writing() {
    // Yeoman automatically calls this method during file generation

    // Write files to the destination directory using a template
    // 1. Template file path
    const tmpl = this.templatePath('foo.txt')
    // 2. Output the destination path
    const output = this.destinationPath('foo.txt')
    // 3. Template data context
    const context = { title: 'Hello zce~'.success: false }

    this.fs.copyTpl(tmpl, output, context)
  }
Copy the code
  • The template approach is much more efficient than manually creating every single file

4.3 Receiving User input

prompting() {
    // Yeoman automatically calls this method when asking the user
    // In this method, the parent class prompt() method can be called to issue command queries to the user
    return this.prompt([
      {
        type: 'input'.// The user input method
        name: 'name'.// Get the result key
        message: 'Your project name'.// Hints for the user
        default: this.appname // appName is the name of the folder where the project is generated
      }
    ]).then(answers= > {
      // answers = { name: 'user input value' }
      this.answers = answers
    })
  }
Copy the code

4.4 Vue Generator Cases

  • The sample code
prompting() {
        return this.prompt([
            {
                type: 'input'.name: 'projectName'.message: 'Your project name'.default: this.appname
            }
        ]).then(answers= > {
            this.answers = answers
        })
    }

    writing() {
        const templates = [
            '.browserslistrc'.'.editorconfig'.'.eslintrc.js'.'.gitignore'.'babel.config.js'.'package.json'.'README.md'.'tsconfig.json'.'public/favicon.ico'.'public/index.html'.'src/assets/logo.png'.'src/components/HelloWorld.vue'.'src/store/index.ts'.'src/App.vue'.'src/main.ts'.'src/shims-tsx.d.ts'.'src/shims-vue.d.ts'.'tests/unit/example.spec.ts'

        ]

        templates.forEach(item= > {
            this.fs.copyTpl(
                this.templatePath(item),
                this.destinationPath(item),
                this.answers
            )
        })
    }
Copy the code

4.5 release the Generator

3. Plop

Plop

A small but beautiful scaffold tool; A gadget to create a specific type of file in your project; Similar to Yeoman’s Sub Generator

  • For example, the React project requires three files each time a page is created
    • Header.css
    • Header.js
    • Header.test.js
  • You can encapsulate this as a template

1. Use of Plop

  • To create the plopfile.js file in the root directory, export a function and receive a plop object
  • Creating a template folderplop-templates/xxxxx.hbs
Import React from 'React' export default () => {<div className="{{name}}"> <h1>{{name}}</h1> </div> }Copy the code


module.exports = plop= > {
    // Arg1 is the name of the generator
    Arg2 configuration option
    plop.setGenerator('component', {
        description: 'create a compoent'./ / description
        // Command interaction
        prompts: [{type: 'input'.name: 'name'./ / key
                message: 'component name'.// Problem description
                default: 'MyComponent'./ / the default value}].actions: [{type: 'add'.// adds the file
                path: 'src/components/{{name}}/{{name}}.js'.templateFile: 'plop-templates/components.hbs'})}}]Copy the code
  • perform
yarn plop component  # (Component is the name of generator)
Copy the code

Conclusion:

Steps to use PLOP

  1. willplopModules are installed as project development dependencies
  2. Create one in the project root directoryplopfile.jsfile
  3. inplopfile.jsScaffolding tasks are defined in the file
  4. Write templates to generate files of a particular type
  5. throughPlopTo provide theCLIRunning scaffolding tasks

4. Working principle of scaffolding

Create a scaffold using NodeJS

npm init
Copy the code
  • Add a “bin”: “cli.js” to pagkage.json

  • In the cli. Js

#! /usr/bin/env node

// The Node CLI application entry file must have such a header
// In Linux or macOS, change the read/write permission to 755

console.log('cli working! ')
// scaffolding-cli


// Scaffolding working process:
// 1. Ask the user questions in cli interaction
// 2. Generate a file based on the user's answer
/ / use the inquirer

const fs = require('fs')
const path = require('path')
const inquirer = require('inquirer')
const ejs = require('ejs')

inquirer.prompt([
  {
    type: 'input'.name: 'projectName'.message: 'Project name'.default: 'scaffolding-cli'
  }
]).then(answers= > {
  console.log(answers)


  // Template directory
  const tempDir = path.join(__dirname, 'templates')
  // Target directory
  const destDir = process.cwd()

  // Output all the files under the template to the destination directory
  fs.readdir(tempDir, (err, files) = > {
    if (err) throw err;

    files.forEach(file= > {
      // console.log(file)
      // Render files through the template engine
      ejs.renderFile(
        path.join(tempDir, file),
        answers,
        (err, result) = > {
          if (err) throw err;

          // Write the result to the destination directory
          fs.writeFileSync(path.join(destDir, file), result)
        }
      )
    })
  })

})



Copy the code