Help you build a systematic understanding of the front end scaffolding

Fish sauce 2021-02-23 04:04:50
help build systematic understanding end

Fish sauce article states : The content is original , Pure technical dry goods sharing and communication , No advertising, no bragging .

Preface : We're building on scaffolding every day , But you really know what scaffolding is , How to build your own scaffolding ? Master the knowledge of front end scaffold , It is an essential part of learning front-end engineering and advanced advanced front-end . This article , I try to put all my knowledge about scaffolding on the tray , In order to help you establish a systematic understanding of the front-end scaffold .

Systematic understanding of the front end scaffold , I start from personal understanding , I've done the following with brain maps :

The next line is , I'm going to focus on this brain map , If you're interested, keep looking down , I hope you can stay on this picture a little longer .

Well , According to the logic in the brain map above , Next, I will divide it into the following parts to discuss this article .

  • Understand the front end scaffolding
  • be based on IDE Set up scaffolding
  • Native scripts build scaffolding
  • be based on Plop Set up scaffolding
  • be based on Yeoman Set up scaffolding

well , After clarifying the way of writing , Let's move on to the first part , Understand the front end scaffolding .

One : Understand the front end scaffolding

When it comes to scaffolding at the front end , You can think of it immediately vue-cli、crate-react-app as well as angular-cli And so on , But in fact , They're not scaffolding , They're just used to create scaffolding Scaffold tools only .

well , Don't sell , Now let's get to understand the concept of scaffold .

1. The concept of scaffolding

In other industries , In fact, we already have the concept of scaffolding . So the concept of front end scaffolding , Just in the development process of front-end engineering , Learn from other industries and gradually stabilize . In Baidu Encyclopedia , The concept of scaffolding is : Scaffolding is a work platform built to ensure the smooth progress of the construction process . The concept is a little strange , We understand :

  • Construction scaffolding

  • Bed scaffolding

Combine these two pictures with the concepts in Baidu Encyclopedia , We should have a clearer understanding of scaffolding . Scaffolding provides a basic working platform , So that the follow-up staff can More standardized and convenient We have to work hard . Based on it , Change it , It can be called the soul description of scaffold .

Back to the front , The staff naturally refers to the front-end developers , The work platform can refer to the whole project , At a small level, it can refer to several associated files or a single file , Even a piece of code . Based on this understanding , We depend on the size of the platform , Scaffolding is classified as follows :

Everyday examples The scaffold / Basic work platform Scaffold type
establish for loop a section for Loop code Code snippet scaffolding
establish html file H5 Template code Single file scaffolding
establish react Components A template .js file 、 A template .css file 、 A template .test.js file Multi file scaffolding
establish react engineering react The template project Project scaffolding

well , After the above analysis and summary , We have basically reached the goal of understanding scaffolding . It's not enough to understand the concept of scaffold to build the front-end scaffold , Next, we use the word template to build a practical understanding of scaffolding .

I blog so hard to share , Isn't it worth your praise and attention ?(^-^

2. Scaffolding and formwork

Scaffolding is a basic working platform , Because this basic work platform is often reused , So there will be a lot of connections between the concept of scaffold and the concept of formwork . I don't want to explain this through too many words , What I want to do is to guide you to connect the two concepts of scaffolding and formwork , And then understand for yourself , The purpose is also to improve your understanding of scaffolding and better understand the idea and process of scaffolding .

With the word template , I'm leading to a couple of projects Scaffolding There are several advantages :

  • Reusable
  • Unification
  • Normalization

3. The idea of front end scaffold construction

Scaffolding is a working platform , For the front end , Scaffold is a carrier of development mode , Its concrete feature is a code segment with specific content 、 One or more files with specific file structure and content 、 A project with a specific file structure and content . So for building a scaffold , Prepare these raw materials ( Specific structure and content , When reusing, it appears as template file or template project ) after , According to certain behavioral logic ( artificial / Script ) Set up scaffolding ( create a file 、 file ) that will do . Of course , Generally speaking, we don't build a scaffold with the same raw materials , We Will receive user input or configuration files and then go to build scaffolding , Realize the partial customization of scaffold .

On the way , You need to code snippets / file / When project content is reused , We usually solve it by manual copying , But it's all fast 2021 Years. , According to the idea that any simple mechanical repetitive work should be done by machines , We should automate to build a scaffold , More convenient , Customize a scaffolding generation tool .

Before discussing the automatic construction of scaffolding , I think it's necessary to reiterate that , The soul of scaffold is not in the process of scaffold construction , It's not about automation , The soul of scaffold lies in raw materials ( It's usually a file template 、 Project template ).

With the above knowledge , Now let's go into the discussion of scaffold construction , As the brain map above shows , In this paper , I'll talk about it in turn IDE build 、 Native script build 、 be based on Plop Build and build on Yeoman There are four ways to build .

well , Let's start with the most acceptable and common one based on IDE Discussion on the way to build scaffolding , This is the way to build scripts for our native scripts and tools .

Two : be based on IDE Set up scaffolding

Let's assume that our requirement is to generate a react hook Components , A code snippet type scaffold . It's a good way to understand , Sir, take a good look at this one below me demo that will do , The following will be divided into the following three steps in order to achieve the scaffolding :

  • Prepare scaffold formwork
  • IDE Registered scaffolding
  • IDE Generate scaffolding

1. Prepare scaffold formwork

Suppose our react hook Component scaffold template , The dynamic part is the template name ( In the following code $0):

import React, { useState, useEffect } from 'react';
import type { FC } from 'react';
export interface $0Props {}
const $0: FC<$0Props> = (props) => {
useEffect(() => {
console.log('init data');
}, []);
return (
<p> $0 component </p>
export default $0;
 Copy code 

2.IDE Registered scaffolding

Open... To configure the code template json file ,vscode Open by :file -> preferences -> users snippets -> typescipt react.

Here we use vscode For example , Other IDE You can search how to configure the corresponding code template .

Here's a look at the above demo Scaffold template configuration :

"react_component": {
"prefix": "rc",
"body": [
"import React, { useState, useEffect } from 'react';",
"import type { FC } from 'react';",
"export interface $0Props {",
"const $0: FC<TestProps> = (props) => {",
"useEffect(() => {",
"console.log('init data')",
"}, [])",
"return (",
"<p> $0 component </p>",
"export default $0;"
"description": "a react component template with hooks"
 Copy code 

After a try , Feeling vscode It's troublesome to configure the code template , Maybe my posture is wrong .

In the above configuration ,

  • The name of scaffold formwork is react_component
  • The input to trigger the template prompt is prefix Configuration item :rc
  • The template content of scaffold is body Configuration item : One row Array ( A troublesome one , Copy it and split it )
  • Scaffolding is described as description Configuration item :a react component template with hooks

3.IDE Generate scaffolding

newly build demo.tsx file , Input rc Trigger IDE The scaffold formwork of the project react_component Code hinting , After selection, we can get our code template .

4. summary

We usually call a code segment scaffold a code template , In fact, it can also be regarded as a kind of scaffold .

Practice has proved , It's very easy to implement this type of scaffolding , Make good use of it , It can improve a lot of development efficiency , After all, we have a lot of repetitive code in our daily development !

in fact , Because of laziness , I seldom use it myself , Or copy and paste more , Ha ha ha .

Code snippet scaffolding doesn't involve file creation , The other three are all about , So we're looking at tools like Plop and Yeoman Build file types ( Projects are also made up of documents ) Before scaffolding , Let's learn the principle of file type scaffolding by exploring native script scaffolding (ps: It's also vue-cli、create-react-app And so on scaffolding tools to create scaffolding principle oh ).

3、 ... and : Native scripts build scaffolding

In order to be closer to the actual development , Here we imitate react-create-app、vue-cli And other scaffolding tools to build scaffolding project practices , Do a simple single file type scaffold construction demo( The same goes for scaffolding with multiple file and project types ).

In the use of react-create-app、vue-cli When scaffolding tools build scaffolding projects , It will Ask some questions first , Then these scaffolds will create a scaffold project based on the answers to these questions and its own project template .

1. Prepare scaffold formwork

<%= param1 %>
 Copy code 

For the sake of understanding , I've made the above template as simple as possible , The dynamic part of the template is param1 Parameters .

Our requirement is to implement a script , This script can be run according to the template content Create a single file scaffold , And in the template param1 Parameters need to be replaced with our input parameters .

2. Write scaffolding creation scripts

We use the idea of functional programming to think about how to write our single file scaffold automation script :

  • Input : Scaffold formwork 、 Template parameters entered by the user
  • Output : Target single file type
  • The mapping relationship : Template parsing 、IO Read, write, etc

With the above ideas , Sure coding Here's the code :

The comments in the code are complete !

const inquirer = require('inquirer'); // Used to interact with the command line
const fs = require('fs');
const path = require('path');
const ejs = require('ejs'); // For parsing ejs Templates
const { Transform } = require('stream'); // For streaming
type: 'input',
name: 'name',
message: 'file name?'
type: 'input',
name: 'param1',
message: 'param1?'
.then(anwsers => {
// 1. According to user input : Get the file name and folder path ( User command path )
const fileName =;
const param1 = anwsers.param1;
const dirPath = process.cwd();
// 2. Get the template file path
const tmplPath = path.join(__dirname, 'template.txt');
const filePath = path.join(dirPath, fileName + '.txt');
// 3. Read the contents of the template file , Write to a newly created file
const read = fs.createReadStream(tmplPath);
const write = fs.createWriteStream(filePath);
// Converted flow : be used for ejs Template parsing
const transformStream = new Transform({
transform: (chunk, encoding, callback) => {
const input = chunk.toString();// Template content
const output = ejs.render(input, {param1}); // Template parsing
callback(null, output);
 Copy code 

The file stream is used in the code , Here is a brief mention of . In the above example, there is no problem without file stream , Because its template file is not big , Direct use readFileSync add writeFileSync Read before you write . File stream is mainly used to solve the problem of too large file content , To prevent the contents of the read file from being too large and occupying too much or even full of the running memory of the program . And the reason we use file streams here , It's to simulate the real complex scaffold .

So painstaking , It's not worth your attention ?

3. Execute scaffolding scripts to create scaffolding

The order is as follows :

c:\workspace\automate node cli.js
? project Name? result
? param1? oooo
 Copy code 

When you look at the above command , I suggest that you use vue-cli and react-creat-app The process of creating a project !

Execution results :

 Copy code 

See the above implementation results , We know that our needs have been successfully realized , The scaffold was built successfully !

4. Sample review

As a simple example , We have already revealed the core principle of our commonly used scaffold .

In order to be more close to our common scaffold , Now let's add a requirement to the native script scaffolding script we implemented above , That is to encapsulate it as a tool , And make it easy to use . After all, for a good automated script and tool , Not only should Powerful 、 Superior performance , It's easier to use .

For the need of instrumentalization , Refer to the practice of mature scaffold tools , We can do this by extracting it into a separate npm cli modular , And link to the global . Besides , If you want to share Go out and offer it to others , So we can put this cli The module is published to github and npm repository in .

well , Next, let's discuss the specific measures .

5. Packaged into scaffolding tool modules

It's very easy to package it as a stand-alone scaffold , Extract templates and scripts into a new npm In the module . Let's talk about how to Configure a normal module into a cli Global module . First of all, it is clearly packaged as npm cli Global module The purpose is to allow other modules to access and call , Follow this idea to find access and call , We configure a normal module to cli modular , This can be achieved through the following steps :

  • For entrance cli Script with header (cli.js)
#!/usr/bin/env node
# Start the script content ...
 Copy code 
  • Configure the entrance (package.json): To configure bin Options { " Command name ": " Entry file path " }
 "bin": {
"testCli": "./cli.js"
 Copy code 
  • Chain to the whole
yarn link
# After success, you can yarn Overall situation bin( Through the command yarn global bin see ) see testCli.cmd file .
 Copy code 
  • Test use
# If you can't find an order , Then consider whether there is no yarn Overall situation bin The path is configured as an environment variable .
 Copy code 

Go through the above steps , You can use the configured bin The command calls this cli modular , It will automatically find this cli Module and execute the scaffolding script .

If you need to be convenient for other people to use , Consider publishing this module to github as well as npm repository in , The idea and steps are as follows :

git init
git remote add origin
git add .
git commit -m "initial"
git push -u origin master
 Copy code 
  • Publish to npmpkg / yarnpkg
# After the authority authentication is passed 
npm/yarn publish
# Be careful 1: When you use a mirror source, you need to add --registry Parameter display specifies push specifies 
npm publish --registry=
# Be careful 2: It's easy to show up npm The same name of the package and the naming problem that triggers spam detection , At this time, you need to modify the package name and publish it again 
 Copy code 

6. practice

After the above practice , We have got through the process of development and release of a simple scaffolding tool . In daily development , For complex scaffolding , We don't usually come from 0 To 1 To implement scaffolding tools , Because it is based on node Of api It takes a lot of attention to write this script IO Read write and template parsing and so on . This is a departure from the original intention , After all, we use scripts or tools for automation to improve efficiency .

Now we stand on the shoulders of giants , Explore how to use Plop Build sheet / Scaffolding with multiple file types , Finally, how to use Yeoman Build a project type scaffold and how to build it based on Yeoman Build a scaffold tool . In order to achieve Improve the efficiency of scaffolding and scaffolding tools Purpose .

Four : be based on Plop Set up scaffolding

Many of my friends may not have been in touch with Plop, Now let's briefly introduce it .

Plop It is a valuable and frequently used tool in daily development , When we come across the need to build a single / Scaffolding requirements for multiple file types , Like building a react Component scaffold ( You need to create a .js Template file 、 One .css Template file and a .test.js Template file ),Plop Would be a good assistant .

As opposed to fully custom implementation scripts / In terms of tools , Use Plop Although it can't be completely customized , But writing scripts under its specifications can call its encapsulated Api, Can achieve Configurable scaffolding tools . It allows us to Focus more on the task itself , Instead of focusing on the implementation details of too many tasks , , in turn, Improve development efficiency .

The principle of scaffolding has been mentioned above , So we're going to focus on Plop Automatic scaffolding workflow , Please refer to the official document for details ,GitHub:Plop repo.

Step1: install Plop Tools

yarn add plop --dev
 Copy code 

After execution of the above order , Will be in node_module The next one is plop Package as well as in node_module/.bin The next one is plop.cmd file , This makes us call Plop Tool time , Use command yarn / npx plop Task name that will do .

Step2: Prepare scaffold formwork

Such as react The goal of the component js file :component.hbs

import React from 'react';
export default () => (
<div className="{{name}}">
<h1>{{name}} Component</h1>
 Copy code 

Step3: To write Plop The task script

First, create a plopfile.js As plop Entry file for executing tasks . Then write the registration task in the entry file that we want it to do , It can be implemented in a configurable way Create scaffolding The function of .

Next we write a plop Automatically create tasks , It's convenient for us to create react Component , It will Automatically create a template based on the predefined template content .js Template content file 、 One .css Template content file and a .test.js Template content file , The implementation code is as follows :

module.exports = plop => {
// generator yes Plop Our mission unit ,component Is the task name 
plop.setGenerator('component', {
description: 'create a component',
// Receive user input 
prompts: [
type: 'input',
name: 'name',
message: 'component name',
default: 'MyComponent'
// Task behavior 
actions: [
type: 'add', // Add representative file 
path: 'src/components/{{name}}/{{name}}.js',// File output location 
templateFile: 'plop-templates/component.hbs'// Template file location 
type: 'add',
path: 'src/components/{{name}}/{{name}}.css',
templateFile: 'plop-templates/component.css.hbs'
type: 'add',
path: 'src/components/{{name}}/{{name}}.test.js',
templateFile: 'plop-templates/component.test.hbs'
 Copy code 

Step4: Use Plop perform Plop Mission

yarn plop component
 Copy code 

Go through the above steps , We can go through Plop Tools rather than native scripts to build a react The need for component scaffolding .

It is suggested to compare the native script mode , Feel the difference between scripted and configured scaffolding .

well , Now, let's go to Yeoman Discussion on scaffold construction .

5、 ... and : be based on Yeoman Set up scaffolding

Yeoman Many friends may not have heard of , Let me give him a brief introduction .

Yeoman It's a modern WEB Application's WEB Scaffold tools , Personally, it is mainly used to create scaffolding of project type . Compared with create-react-app、vue-cli For scaffolding tools that focus on a certain frame ,Yeoman It's a more general scaffolding tool .

Next, let's start by using someone else's project template (generator), Omit the steps we take to build our scaffolding project template , In order to simplify your understanding Yeoman Workflow of building a scaffold project . Then we use our own custom scaffold project template to build the scaffold , Realize the final construction of project type scaffold .

The soul of scaffolding never lies in the way it is built , It's not about automation , It's the scaffold template ( Template code block / Template file / The template project ), It's important to know that .

Let's start from Yeoman Official generator repo Take one out of the middle node Project template , Build a scaffold , As Yeoman The workflow of building project type scaffold is discussed .

1. Use someone else's project template to build a project

Step1: install Yeoman

yarn global add yo
 Copy code 

Step2: Install project templates :generator

The following example installs a node Project template

// generator repo
yarn global add generator-node
 Copy code 

Step3: Use yo function generator Create template project

Project template name generator-, Can be used as yo To create a project

yo node
 Copy code 

2. Build a project using a custom project template

Step1: install Yeoman

yarn global add yo
 Copy code 

Step2: Prepare project templates

As below Vue Template project directory structure :

Step3: Write your own generator modular : The logic of creating a project from a template project

Here is a simple custom implementation generator: Copy and parse the template project, create a project to the current path

  • With generator- Start by creating and initializing a module project (generator-demo)
  • Copy the project template to the current module
  • To write generator Entrance file : Parse project template, create project
const Generator = require('yeoman-generator')
module.exports = class extends Generator {
// Receive user input
prompting () {
return this.prompt([
type: 'input',
name: 'name',
message: 'Your project name',
default: this.appname
.then(answers => {
this.answers = answers
// Create a new project based on user input and template project
writing () {
// Here the file name list should use IO Script read
const templates = [
templates.forEach(item => {
// utilize fs Of copyTpl Method : analysis ejs Put the template file in the target path
 Copy code 
  • Use yarn link Link the current module to the global for use yo find
  • Selectively generator The module is published to GitHub、npm as well as generator repo in

The idea and implementation have been mentioned above , I will not expand here .

Step4: Use yo function generator Create template project

yo demo
 Copy code 

Go through the above steps , That is, we can create our own custom project template . Be able to reuse template projects built by yourself , But the only way to architects !

It's over , Writing is not easy to , Don't forget to give a little praise and attention . mua (*◡‿◡)

本文为[Fish sauce]所创,转载请带上原文链接,感谢

  1. JavaScript advanced: Javascript object-oriented, JavaScript built-in object, JavaScript BOM, JavaScript encapsulation
  2. JavaScript advanced: Javascript object-oriented, JavaScript built-in object, JavaScript BOM, JavaScript encapsulation
  3. Vue determines whether the El form in the elementui is updated or changed. If it changes, it will prompt whether to save it. If it does not change, it will leave directly
  4. Algorithm problem: sum of two numbers -- JavaScript and Java implementation
  5. High performance nginx HTTPS tuning
  6. JQuery advanced
  7. day 30 jQuery
  8. JQuery:JQuery Basic syntax, jQuery selector, jQuery DOM, comprehensive case check box, comprehensive case random picture
  9. TCP/IP 开胃菜 之 HTTP
  10. JQuery:JQuery Basic syntax, jQuery selector, jQuery DOM, comprehensive case check box, comprehensive case random picture
  11. JavaScript data type
  12. [micro front end] the final chapter of micro front end - Qiankun guide and overall exploration of micro front end
  13. Solve Ajax cross domain problem [5 solutions]
  14. HTTP of TCP / IP appetizer
  15. Optimization of pod creation efficiency in serverless scenario
  16. Iqiyi Sports: experience the ultimate expansion and contraction of serverless, and increase the utilization rate of resources by 40%
  17. First knowledge of HTTP / 1.1
  18. First knowledge of HTTP / 1.1
  19. Webpack learning notes series 05 devserver
  20. Webpack learning notes series 04 - resource processing optimization
  21. How to build a high performance front end intelligent reasoning engine
  22. How to become a professional front end engineer in 2021?
  23. How to transform single / micro service application into serverless application
  24. How to transform single / micro service application into serverless application
  25. How to transform single / micro service application into serverless application
  26. How to connect the ground gas to the micro front end?
  27. How to connect the ground gas to the micro front end?
  28. How to connect the ground gas to the micro front end?
  29. Vue server rendering principle analysis and introduction
  30. Realize the correct loading of text message
  31. Building my own project scaffolding with yeoman
  32. JavaScript advanced prototype and prototype chain
  33. React background management front end system (based on open source framework development) start
  34. JS practical skills breakpoint debugging
  35. I'd like to share with you 20 super easy-to-use Chrome extension plug-ins
  36. Get page element location
  37. Use the powerful API of modern browser to record any interface in the browser and realize export, save and management
  38. Delayed code execution in flutter
  39. Reconfiguration experience of KOA middleware system
  40. Add comments to your blog
  41. Svg editor -- new path
  42. Detailed explanation of debounce and throttle of JavaScript function
  43. Anti shake and throttling and corresponding react hooks package
  44. C2m: the first CSDN article moved to MOOC script 5000 words, detailed painstaking development process, there are renderings and source code at the end of the article
  45. Front end, school recruitment, Taobao, guide
  46. [vue2 & G6] get started quickly
  47. Canvas from the beginning to the pig
  48. Take five minutes to standardize the code comments?
  49. Some thoughts on sass
  50. what?! You haven't filled in the award information yet
  51. How to get the interface + tsdoc needed by TS through swagger
  52. Binary tree
  53. Canvas drawing method in Web screenshot
  54. Front end docker image volume optimization (node + nginx / node + multi-stage construction)
  55. Become a big influence of technology? Coding pages quickly build personal blog
  56. Object and array deconstruction, spread operator, rest operator
  57. Analysis of Axios source code
  58. Two ways to delete useless code in project (Practical)
  59. Edit your picture with canvas
  60. Today's chat: 2-4 years to walk out of the resignation dilemma and comfort zone