Overview of front-end engineering

Front-end engineering defines and solves major problems

As it is now being developed, the front end can be responsible for more and more, and is no longer limited to the web page. Things like apps, mini programs, and even desktop applications can be developed using front-end technologies.

So the original write Demo through the front end, back end set of data model has long been unable to support modern diversified front-end development.

In this context, front-end engineering has become an important technology and is one of the necessary technologies for front-end development.

Technology exists to solve problems, and front-end engineering solves many of them. For example, ES6 new syntax, Less/Sass/PostCss CSS tools and modularity. They are not directly supported by the runtime environment. But with front-end engineering, you can turn them into code that the runtime environment supports.

There are also actions required to deploy the project, such as compressing code and resource files, uploading the code to the server, and so on. If these tasks are handled manually by a human, it’s easy to make mistakes. In this case, it makes more sense for the machine to do these tasks automatically.

When multiple people collaborate, code style and code quality need to be ensured.

The development process needs to wait for the back-end interface to be completed in advance.

These are the areas that front-end engineering is responsible for.

To sum up, front-end engineering to solve the problem mainly has six parts.

  1. A weakness of traditional language or grammar. (ES6+ syntax, TypeScript, Sass)

  2. Unable to use modular/Components (ES Modules, Components)

  3. Repetitive mechanical work (Build, Publish)

  4. Code style unity, quality assurance (Git, ESLint)

  5. Rely on back-end service interface support (Mock)

  6. Overall reliance on back-end projects (DevServer)

Engineering performance

All the means to improve efficiency, reduce costs, and ensure quality for the purpose of engineering.

All repetitive tasks should be automated.

The overall process of a regular front-end project consists of approximately 5 steps:

Create project – Code – Preview/test – Commit – deploy

1. Create project phase:

Automatically create a project directory structure and specific types of files with the scaffolding tool.

2. Coding stage:

You can use tools to format your code, validate your code style, and use new features to write your source code and compile/build/package to generate runtime code supported by your runtime environment.

3. Preview/test phase

The development process, which requires Mock services, requires the use of basic Web servers to host projects such as Nginx, Apatch, and so on. However, none of these services provide a hot update experience, so modern tools are needed to enhance the development experience.

After compiling the transformation, you need to locate the source code if an exception occurs. This requires the use of Source Map technology to Map the running code and Source code.

4. Code commit phase

Use git hooks to check the entire project, both for code style and project quality, to ensure that no code is committed to the Git repository and that the git repository code is always available. In addition, you can also restrict the format of git logs, which can be of great value when branching and rolling back code.

Lint-passage and continuous integration are the main tools.

5. Deployment phase

CI/CD, automatic publishing.

The project can be automatically packaged and uploaded to the FTP server with a single command.

Engineering does not equal tools

Now some tools are so powerful, like Webpack, that many people think of front-end engineering as Webpack.

In fact, tools are not the core of engineering; the core of engineering is the overall planning and architecture of the project. Tools are just one way to implement this planning and architecture.

Engineering of a project, first of all to plan a project overall workflow architecture.

Examples include file organization (hierarchical by role, hierarchical by business), code development paradigm (syntax, specifications, standards, languages such as ES6+, TypeScript, etc.), front end separation (Ajax and middle tier).

After planning the overall workflow architecture, consider which tools to use to implement the plan.

We can learn from the current mature engineering solutions in the industry, such as create-React-app, Vue-cli, Angluar-cli, Gatsby – CLI, etc.

They are not a simple project generation scaffold, but an integration of engineered tools.

Engineering and Node.js

The current engineering of the front end is largely due to Node.js.

Node.js is the first industrial front-end revolution after Ajax. Without Node.js, there would be no front-end today.

Most engineering tools are currently developed by Node.js, so front-end engineering is strongly driven by Node.js.

In short, engineering exists to solve problems.

Scaffolding tool

The profile

Scaffolding tools are the originators of front-end engineering, tools that automatically help us create project infrastructure and provide project specifications and conventions.

When developing the same type of project, there are many things that are the same, including:

The structure of the organization

Development paradigm

Module is dependent on

Tool configuration

Based on the code


These same things don’t need to be created manually, and you can quickly create the skeleton of the project using the scaffolding tool. And then build on that skeleton.

For example, the process of creating projects using large ides such as IDEA and Visual Studio is a scaffolding workflow.

The scaffolding on the front end is not quite the same as for server and mobile projects. Because the technology selection is too diverse to focus on a particular IDE, it is now popular to do project creation on the command line.

Commonly used scaffolding tools

React project: create-react-app

Vue project: Vue – CLI

Angular project: Angular-CLI

They create a project infrastructure based on information selected by the user, but they only serve their own framework and are not universal.

The other category is the universal scaffold tool, represented as Yeoman. The advantage is that it is flexible and easy to expand.

Another category is used during project development, such as Plop. It can create a specific type of file. For example, the code underlying a module or component.


Yeoman is one of the oldest, most powerful, and most versatile scaffolding tools available, and is developed based on Node.js.

Yeoman is more like a platform for scaffolding than a regular scaffolding tool.

We can define the Generator to create our own project scaffolding.

The downside of Yeoman is that its advantage is its lack of focus, which makes it inferior to tools like Vue-CLI in the scaffolding process of focusing on a particular framework.

The basic use

1. Install Yeoman globally.
npm i -g yo
Copy the code

After yo is installed, you can check the version number to see if the installation was successful.

yo --version
Copy the code
2. Install the Generator.

It is not enough to just install YO. It is just a Generator running module, and you need to install a specific Generator.

A Node project, for example, requires the installation of Generator – Node.

npm i -g generator-node
Copy the code
3. Run the generator by running the yo command.

Once the installation is complete, you can create the Node project.

The command is yo plus the name of the generator. (Node package name without generator-)

yo node
Copy the code

During project creation, Yeoman asks questions and uses the answers submitted by users to create different project structures.

Sub Generator

Each generator can provide sub generators that generate specific files or base code. However, not every generator provides a sub generator. For details, see the official document of the generator.

It’s also easy to run the sub generator, which is yo plus the name of the generator, plus a colon (:), and then the name of the sub generator.

For example, create a command in the Node.js project.

yo node:cli
Copy the code

Yeoman uses step summary

There are roughly six steps.

  1. Identify project requirements.
  2. Find the appropriate Generator.
  3. Install Generator globally.
  4. Run the corresponding Generator through yo.
  5. Fill in the build options interactively on the command line.
  6. Generate the required project structure.

A custom Generator

Because the official generator can be very limited in some scenarios, it is necessary to customize your own generator.

Creating a Generator module

A generator is essentially an NPM module that conforms to a specific structure.

The name of the generator must be in the format generator-


A generator requires a base class for a generator.

The overall operation steps are as follows.

Create the project root directory.

mkdir generator-sample
Copy the code

Initialize the project.

npm init -y
Copy the code

Install the yeoman – the generator.

npm i yeoman-generator
Copy the code

Create specific folders as required by the project structure.

The entry file is generators/app/index.js.

This file needs to export a class that inherits from Yeoman Generator. The Lifecycle functions in this class are automatically called by the Yeoman Generator as it works.

In this exported class, you can invoke the utility methods provided by the parent class to implement some specific functions.

For example, you can create files in the Writing lifecycle function.

const Generator = require("yeoman-generator");

module.exports = class extends Generator {
  writing() {
    // Template file path
 const tmpl = this.templatePath("foo.txt");  // Output the target path  const output = this.destinationPath("foo.txt");  // Template data context  const context = { title: "Hello".success: false };   this.fs.copyTpl(tmpl, output, context);  } }; Copy the code

The operation file can use the methods under the this.fs module provided in the parent class. Unlike the nodeJS native FS, this FS is highly encapsulated and therefore more powerful.

Create files from the template

If a project needs too many files, it is difficult to create files one by one. In this case, using templates to create files is more convenient.

Create a templates folder in the generators/app directory. This folder will be filled with template files. Can be obtained by the this.templatepath method.

The template file follows the EJS syntax entirely, which is how Angle brackets are written.

<%= name %>
Copy the code

EJS template official website: https://ejs.co/

Finally, copy the template to the target directory using the this.fs.copyTpl method.

The template approach is much more efficient than creating each file manually.

Receive user input data

Dynamic data in a template needs to be entered by the user, typically by a query on the command line.

The Prompt method of the parent class can be called in the promting lifecycle function to initiate the query, which returns an asynchronous function.

const Generator = require("yeoman-generator");

module.exports = class extends Generator {
  prompting() {
    // The prompt argument is an array that can initiate multiple questions
 // Each problem is represented as an object  // Type is the type of the problem. Input means that the user is required to input.  // Name is the key of the problem  // Message is an indication of the problem  // Default is the default value when the user does not input  return this.prompt([  {  type: "input". name: "name". message: "Your project name". default: this.appname,  },  ]).then((answers) = > {  // Answers is returned as an object  // { name: 'user input value' }  // Mount the object to this.answers  this.answers = answers;  });  }  writing() {  // Template file path  const tmpl = this.templatePath("foo.txt");  // Output the target path  const output = this.destinationPath("foo.txt");  // Replace context objects with user input objects  const context = this.answers;   this.fs.copyTpl(tmpl, output, context);  } }; Copy the code

Vue Generator project case

You can first generate a basic VUE project skeleton with vue-CLI, and then use this skeleton as the base template. Anything that needs to be replaced by a variable is replaced using EJS syntax.

All files in the template are called this.fs.copyTpl by traversal in the writing lifecycle function.

I won’t show you how to do that.

Release the Generator

The distribution process of the generator is the same as that of a normal NPM package. It is published using the NPM publish command.

If you want to be officially included by Yeoman, you need to add yeoman-generator to the keyword.


In addition to large scaffolding tools like Yeoman, there are many small and beautiful scaffolding tools like Plop.

Plop is often used to create a certain type of file during the development of a project, with advantages similar to the concept of sub Generator in Yeoman.

Application scenarios

For example, in the React project development process, developing a component required creating a directory, which required three files.

| |____Footer.tsx
| |____Footer.scss
| |____Footer.test.ts
Copy the code

If we manually created these files and wrote generic code, the process would be tedious, so we can use Plop to do this.

The Plop usage

Start by adding plop to your project.

npm install --save-dev plop
Copy the code

Create the plopfile.js file in the project root directory, which is the entry file required for plop work.

A simple plopfile.js configuration is as follows:

// Export a function
// This function needs to take a plop object argument
module.exports = (plop) = > {
  // Call the setGenerator method
  // The first parameter is the command name and the second parameter is the configuration object
 plop.setGenerator("component", {  description: "create a component"./ / that  / / to ask  prompts: [  {  type: "input". name: "name". message: "component name". default: "MyComponent". }, ]. / / action  actions: [  {  type: "add".// Add the file  // Use {{}} syntax to get the value asked above  path: "src/components/{{name}}/{{name}}.tsx". // File path of the template  templateFile: "plop-templates/component.hbs". },  // Add SCSS file and test file  {  type: "add".// Add the file  // Use {{}} syntax to get the value asked above  path: "src/components/{{name}}/{{name}}.scss". // File path of the template  templateFile: "plop-templates/component.scss.hbs". },   {  type: "add".// Add the file  // Use {{}} syntax to get the value asked above  path: "src/components/{{name}}/{{name}}.test.ts". // File path of the template  templateFile: "plop-templates/component.test.ts.hbs". }, ]. }); }; Copy the code

Above the HBS file follow the grammar of the handlebars, specific reference: https://handlebarsjs.com/

Templates are usually stored in the root directory in the pplo-templates folder.

Finally, you can run the plop script through the command.

npx plop component
Copy the code

In summary, there are five steps to use PLOP.

  1. Install the PLOP module as a project development dependency.
  2. Create a plopfile.js file in the project root directory.
  3. Define the scaffolding task in the plopfile.js file.
  4. Write a template to generate a specific type of file.
  5. Run the scaffolding task through the CLI provided by Plop.

Working principle of scaffolding and simple Demo development

Scaffolding works on a relatively simple principle, basically asking the user some questions at startup and using the answers together with the template to generate the corresponding files.

Ideas for developing scaffolding:

  1. Ask customer questions through command line interaction.

  2. Generate files based on the results of user responses.

Create the scaffold project folder.

mkdir sample-scaffolding
Copy the code

Initialize the project.

npm init -y
Copy the code

Add the bin field to package.json to define the cli entry file.

  "bin": "cli.js"
Copy the code

Create a cli. Js.

touch cli.js
Copy the code

Since you need to question the user on the console, you use a NodeJS library, the Inquirer.

npm i --save-dev inquirer
Copy the code

In addition, you need to use the template engine to inject variables into the template file, so you need to use EJS.

npm i ejs
Copy the code

You can now write the logic in cli.js.

#! /usr/bin/env node

const fs = require("fs");
const path = require("path");
const inquirer = require("inquirer");
const ejs = require("ejs");  // After the command is executed, the query is initiated directly. inquirer  .prompt([  {  type: "input". name: "name". message: "Project name?". },  ])  .then(  The return value anwsers is an object  (anwsers) = > {  // The template directory  const tmplDir = path.join(__dirname, "templates");  // The target directory  const destDir = process.cwd();  // Copy all the template files in the template directory to the target directory after conversion by the template engine  fs.readdir(tmplDir, (err, files) => {  if (err) throw err;  // Iterate through all template files  files.forEach((file) = > {  // Render the file via ejs  ejs.renderFile(path.join(tmplDir, file), anwsers, (err, result) => {  if (err) throw err;  // Write the ejS rendered file to the object file  fs.writeFileSync(path.join(destDir, file), result);  });  });  });  }  ); Copy the code

The first line of #! /usr/bin/env Node tells the system that the file is executed through node.

Next, create the template folder.

mkdir templates
Copy the code

Create template files index.html and style.css.

Index.html content:

<html lang="en">
    <meta charset="UTF-8" />
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0" />
 <title><% = name% ></title>  <link rel="stylesheet" href="./style.css" />  </head>  <body>  hello, world!  </body> </html> Copy the code

Style. The CSS content:

body {
  background-color: #ddffdd;
  color: # 060606;
Copy the code

Link commands to global.

npm link
Copy the code

At this point, a simple scaffolding demo is developed.

Now to start testing, go to another directory and create a project directory.

mkdir test-project
Copy the code

Go to the directory and run the scaffold command.

Copy the code

At this point, the command line will be asked, enter the project name, you can see the generated file.

? Project name? hello
Copy the code

Write in the last

The scaffolding tool is the first piece of front-end engineering. This is the end of the story. There will be several more articles on front-end engineering.

– END –