What is front-end engineering? Essentially is the front-end development process, standardization, standardization, tool, automation, simplification. Improve front-end application quality and development efficiency through specifications and tools

1. The scaffold

Scaffolding is used to quickly generate directory templates for new projects and integrates a series of systematic tool installations to improve front-end developer productivity and reduce copy operations

1.1 Common scaffolding tools

  • Vue official scaffolding: VUE – CLI

Vue CLI is a complete system official document for rapid development based on Vue. Js 🚀

How to install

npm install -g @vue/cli-service-globa
Copy the code

How to create a project quickly

vue create admin-template
Copy the code

There are two creation modes, one is default configuration (no NPM package with other auxiliary features) and the other is manual configuration (can be configured according to production needs).

  • Yeoman

Official introduction: Yeoman helps you launch new projects, define best practices and tools to help you stay productive, and is a scaffolding underlayer framework that you can also customize your own scaffolding implementation with Yeoman.

Yeoman mainly includes: Yo (scaffolding, automatic generation tool), Grunt, gulp (build tool), Bower, NPM — (package management tool), etc

How to install

npm install -g yo  
Copy the code

The Yeoman community has different project directory templates with the option of viewing links or wrapping their own scaffolding with yeoman-Generator

1.2 Develop scaffolding tools

If the existing scaffolding customization and customization are not high, the team needs to customize scaffolding tools suitable for their own development. The common tool libraries involved in scaffolding tool development are listed below: 👇

  • Child_process: Used to execute shell commands
  • Commander: Used to handle console commands 🔗 use documentation
  • Inquirer: For the console 🔗 use documentation
  • Semver: for version checking hints 🔗 use documentation
  • Fs-extra: For fs operation inquiries 🔗 use documentation
  • Execa: Used to execute terminal commands 🔗 Use documents
  • Chalk: used for multicolored console 🔗 use documentation

For more information about scaffolding practices on projects, read Tree Jam’s Developing Simple Scaffolding from zero to one.

1.3 Template Management

After reading the first two sections, you may feel that configuring and developing scaffolding is a lot of work for smaller teams. You can do this by generating a unified template and then maintaining it with warehouse management. Next time you need to create a new project, you can pull the template directly from the warehouse

1.4 summarize

Scaffolding can increase the efficiency of the project initialization structures and reduce the time consumed by a building project, team scale have conditions can be internal scaffolding tools, developed for the small team, develop scaffolding tools “output ratio is not high, after all, scaffolding tools to complete the project initialization, scaffolding and useless, So if it’s not “cost effective” for a small team to invest the time to develop a scaffolding tool, the easy way is to set up an internal template management system, which can be managed with Git or SVN

2. Build tools

What are build tools? Build tools can make us better automated processing including (es6 conversion, CSS, js compression, less and sass conversion, etc.), let we no longer need to manually to repeat to do these things, the liberation of the hands of developers, to better focus on the business development, build is essentially the code “string” rise, then compress and confusion, The end result is an object code file. Common building tools include Webpack, rollup, Parcel, Grunt, and gulp

2.1 Webpack

Webpack is a front-end packaging tool, by analyzing the directory structure of the project, find modules and dependencies between modules, and the browser can not directly run languages such as typescript, CSS preprocessor syntax (less, SASS) or because the browser does not support new built-in functions at the end of the version. It needs to be transformed and packaged into a browser-supported format, with 👇 being the main feature

  • CSS preprocessors such as LESS and SASS are not supported by browsers
  • Some browsers of earlier versions do not support the ES6 syntax, so you need to convert it to the ES5 syntax for use by the browser
  • The project has too many dependencies, too many files, and the need to convert complex code structures into refinements
  • Modular packaging, retain the maintainability of a single module, and reduce the number of HTTP requests, optimize the loading speed

For more information about webpack practice in projects, you can read Shujiang’s “[Webpack] Migration and Practice from VUE-CLI 2X to 3X”.

For more webPack configuration and learning, read the following article at 👇

  • Webpack: From getting started to real project configuration
  • Configuring WebPack from scratch (based on WebPack 4 and Babel 7 versions)
  • Deep Unlock Webpack series (Advanced)

2.2 a Rollup

Rollup is a good way to package JS SDKS or packaged frameworks with tree-shaking, and webpack, as described in the previous section, is a good way to package applications such as SPAs or homogeneous projects

Read Tree Jam’s Front-end JS-SDK Stuff about Rollup in the project.

For more Rollup configuration and learning, read the following article at 👇

  • All that Rollup stuff

2.3 Parcel

Parcel is a Web application packaging tool for developers with varying experience. It takes advantage of multi-core processing to provide extremely fast speed and does not require any configuration official link 🚀

The biggest difference between Parcel and webPack is that there is no need to maintain a configuration file, as an example: If you want to convert the syntax for less, you need to configure less-Loader in WebPack to do this, and Parcel does not need to install less, and Parcel will automatically convert when it detects a Less file. In other words: Parcel can complete a project build without configuration, simple!


The advantage: Faster packing time, too! 🚀

For more configuration and learning, read the following article at 👇

  • From WebPack to Full Embrace Parcel #1 Explore Parcel

2.4 Package management tool build NPM

Build operations can be performed using NPM scripts, writing the corresponding commands in Packjson by executing NPM run [task], as shown below 👇

"scripts": {
    "serve": "vue-cli-service serve ".    "build": "vue-cli-service build".    "build_development": "vue-cli-service build --mode development".    "build_test": "vue-cli-service build --mode test". "build_preproduction": "vue-cli-service build --mode preproduction". "build_production": "vue-cli-service build --mode production". "unit": "jest --config src/test/unit/jest.conf.js --coverage". }, Copy the code

Define different execution commands based on different tasks

2.5 summarize

  • Webpack: Suitable for large-scale project construction: Webpack has the most perfect ecology, more application scenarios, high community popularity, and a powerful loader and plug-in ecology
  • Rollup: Library-focused packaging: Modules can be packed into a single file, tree-shaking to remove useless code and reduce code size, but without webPack’s powerful plug-in ecosystem, positioning is better for library-focused packaging
  • Parcel: No configuration, fast and efficient packaging, but not tree-shaking, resulting in large output files
  • Grunt, gulp: suitable for project tool flow construction, slowly replaced, not recommended

3. The Mock services

Mock refers to is to solve the front in the page set up finished, now need to alignment backend interface, the backend interface has not yet developed, also can’t alignment at the front end can be in accordance with the first with the back-end constraints in advance good data structure to simulate the interface data to walk the development (usually by the backend interface document Swagger, for example), realize the real separation of front and back side

Front-end mocks mainly include the following methods:

  • Data interception type
  • Json – server service
  • Visual interface management platform

3.1 Data interception

Data interception refers to the interception of real request to the corresponding matching interface through simulated Http request and return simulated data. At present, the main tools are as follows: 👇

  • mockjs

Mock.js is a Mock data generator designed to help front-end attackers develop independently of the back-end, help write unit tests, and generate and return Mock data official documents by simulating Ajax requests

How to install

npm install mockjs;
Copy the code

How to use

For more mock example syntax 👉 click me

//mock.js
const Mock = require('mockjs');
Mock.mock(new RegExp('/user/info'), 'get', {
        'code': 0.        'msg': 'success'. 'data': {  "content|15": [{  "startTime": "@date('yyyy-MM-dd')". "createUser": '@cname'// The name is a random Chinese name "endTime": "@date('yyyy-MM-dd')". "ago|18-28":25, // Random number of ages 18-28 "sex|1": ["female"."male"], // Return a random object in the array "ud": "@increment"/ / since the increase}]. } }) Copy the code

Mock. Js is introduced in main.js to determine the context of the project and only in the mock context

import Vue from 'vue'
import App from './App'
import router from './router'
import axios from 'axios';
if(process.env.NODE_ENV === 'mock') { require('./mock.js') } Vue.prototype.$axios = axios;  new Vue({  el: '#app'. router,  components: { App },  template: '<App/>' }) Copy the code

The mock will intercept the backend and return the interface data we set as follows: /user/info

 axios.get('/user/info', {}}).then(res=> {
    console.log(res);
 })
Copy the code

As shown in 👇, you can see that the mock data we defined was returned successfully. The interception method can only view the data returned through the console, because the request cannot be seen in The Network of Chrome, which is also a disadvantage of Chrome

3.2 JSON-server Service type

Json-server is a Node module. By running Express server, you can directly use a JSON file as a Web server with full RESTful API and support cross-domain, JSONP, routing customization and other functions. You can also combine this with mock.js, introduced in the previous section, to achieve the effect of mock data

Json-server has the advantage of being able to see real network requests and the disadvantage of being able to run a Node service, compared to the mock.js data interception approach mentioned in the previous section

  • How to install
npm install -g json-server
Copy the code
  • How to use
json-server --watch db.json
// db.json is the mock data sourceCopy the code

3.3 Mock Interface Management Platform

The previous section covered the use of data interception, but if it is inconvenient to maintain such “data” on a large team with multiple projects, is there a better way?

Manage platforms through mock interfaces, such as RAP, easy-Mock document links, and YApi document links. Here’s YApi

  • YApi

YApi is an efficient, easy-to-use, powerful API management platform, which aims to provide more elegant interface management services for developers, products and testers. It helps developers easily create, publish, and maintain apis

Compared with the data interception type described in the previous section, YApi supports the creation of projects based on Swagger, saving the time of manual creation, so that the interface structure of each module can be quickly generated, and you can save the tedious manual adding operation

Select Data Management, enable URL import, and enter swagger interface document link


3.4 summarize

If a team project is small, the use of MockJS (data interception) is recommended for easy change, but if the project is large, multiple people collaborate, and the requirement interface changes quickly, the use of mock interface management platform is recommended

4. Front-end specifications

As front-end engineering becomes more and more mature, code standardization plays a great role in improving development efficiency, including late maintenance. Unified specification can save the time cost of handover, and the specification includes directory structure, code quality (naming, annotation, JS specification, CSS specification, indentation, etc.).

4.1 Directory Structure

Standardize the project’s SRC directory based on the business model

Static resource directory: AssetsLocal data simulation directory: MocksPublic function method directory: utilsUnit Test directory:test
Constant directory: constsIcon directory: ICONSCommon mixing functions directory: mixinRoute directory: RouterComponent directory: ComponentsPage Contents: ViewsConfiguration directory: configService API Interface management directory: APIVuex status pipeline directory: StoreEnv *: In a project we usually use environment variables to influence the behavior of the application in different runtime environments. Read environment variables from a fileCopy the code

4.2 Syntax Constraints

  • Componentized naming rules
  1. Name it according to the function: for example, the Header is Header and the Header navigation bar
  2. Group pieces by page: NewsItem, for example, can be used for a list of articles, or for content recommendations on a detail page
1. Component file names always start with uppercase words such as :(PascalCase)2. When declaring a prop, it should always be named using the camel's name3. Component names should be full words, not abbreviationsCopy the code
  • Vue specification
1. Always use a key with V-for2. Never use v-if and V-for on the same element.3.Object.freeze method to freeze an Object that will not change, reducing component initialization time4. Each componentexportMethods in default {} are in the same order to facilitate the search for corresponding methods.According to Data, props, hooks, Watch, computed, components5. Add the data type, required or not, and the default value to props for checking errors and making the transmission more rigorous6. Use timers, clear timers in the beforeDestroy() life cycleCopy the code
  • CSS

As the number of project modules increases, it is important to regulate the SYNTAX of CSS to prevent conflicts between CSS definitions in different pages or components.

.user-info {} # user-info is a block, I understand a module
.user-info--feature {} # user-info--feature is a modifier to indicate the different states of this block
.user-info__title{} # user-info__title is an element that belongs to the userinfo module and is a block of multiple elements
Copy the code

4.3 Development tool specifications

  • eslint

A plug-in javascript code detection tool, which can be used to check common javascript code errors, as well as code style checking

Two extensions are recommended (🚀 & eslint-plugin-vue: 🚀)

  • Prettier

Is a formatting code tool. Used to keep the team’s project style consistent

  • stylelint

Stylelint is a CSS code review tool for constraining CSS writing specifications, enhancing code readability, and official documentation

For details, please read Tree Jam’s Front-end Specification Stuff.

4.4 Git Commit Specifications

The Commit specification can better form a clear commit record (Changelog). The corresponding COMMIT Message specification can constrain developers to add comments according to different commits. The common categories are as follows

  • The constraint definition
Feature: Develop new featuresFix: fix the bugRefactor: Code refactoringDocs: Document modificationStyle: Code format modification, note not CSS modificationtest: Test case modificationPerf: Improves performanceBuild: Change project builds or external dependencies (e.g. scopes: webpack, gulp, NPM, etc.)Revert: Code rollback Such as:git commit -m 'Fix: Fix xyz bug' Copy the code

In addition to the simple specification above, you can also integrate Commitlint configuration. The next section will teach you how to do it. If you are interested, check out the official documentation at 👈,

  • Automatic detection

So how do you configure it on vue-CLI? Git Hook vUE -cli3x It encapsulates yorkie, which is essentially a custom change to fork husky so that hooks can be read from the “gitHooks” property of package.json. The gitHooks configuration is combined with Commitlint to automate detection of commit logs, as shown in the flowchart 👇


Install commitlint

npm install -g @commitlint/cli @commitlint/config-conventional
Copy the code

Create the Commitlint configuration file

/ / new commitlint. Config. Jsmodule.exports = {
  extends: ['@commitlint/config-conventional'].  rules: {
    'type-enum': [
 2,  'always'. [  'feature'// Develop new features 'fix'// Fix bugs 'refactor'// Code refactoring 'docs', // Documentation 'style', // format (changes that do not affect code execution) 'test'// Add tests 'build', // Change project builds or external dependencies (e.g., Webpack, Package, etc.) 'revert', / / rollback 'perf'// Improve performance].]. 'type-empty'A: [2,'never'], // Submissions that do not conform to the specification can also be submitted, but with a warning 'subject-empty'A: [2,'never'], // Submissions that do not conform to the specification can also be submitted, but with a warning 'subject-full-stop': [0, 'never']. 'subject-case': [0, 'never']. }, };  Copy the code

Configuration gitHooks

// package.json
"gitHooks": {
    "pre-commit": "lint-staged".    "commit-msg": "commitlint -E GIT_PARAMS"
  },
 "lint-staged": {  "*.js": [  "vue-cli-service lint" ]. "*.vue": [  "vue-cli-service lint"  ]  }, Copy the code

4.5 Document Constraints

If the team is small, we can refer to the front-end specifications of first-tier Internet companies, unify the code style,

  • Jingdong concave laboratory code specification
  • clean-code-javascript
  • Someone whose team
  • Baidu FEX team

Unit testing

Unit testing is a part of engineering to ensure project quality and code quality. Although testing cannot directly reduce bugs, it can reduce the bugs generated in the process of repeated modification, because when you modify the code, it is easy to ignore some logic set before, leading to system failure

5.1 Preparations

  • Select a unit testing framework: Jest, Mocha, Karma, etc
  • Develop test rules
  • Constrain the team unit test coverage minimum: for example, if the function coverage is 80%, the project will fail to release every time the automated tests fail to meet this condition until the target condition is completed

5.2 Following Rules

No matter what unit testing framework is used, the basic principle is to rely on the following 👇

  • Assumptions:Test ('formatTime() ', () => {})Specifies the conditions to be met to complete the test
  • When: The operation to be performed, such as:date.formatTime(1586934316925)Execute the test for this function
  • Then: the result of getting both assertions such as:Expect (date. FormatTime (1586934316925, 'yyyy. MM. Dd)). The place (' 2020.04.15');

Read Tree Jam’s Front-end Unit Testing Thing for more.

6. Project deployment

After the completion of project development, online deployment is also an important part of engineering, and for the front-end project, deployment is not a painful thing

At present, most OF THE SPA is just a simple static resource file, which can be packaged directly, and then use Nginx as a proxy to complete simple deployment. It can also be combined with Docker and Jenkins to do automatic deployment, continuous deployment and continuous integration.

For the front-end application rendered by the server side, the deployment is relatively more links, but also need to manage the process, monitor the service is normal, etc., which involves the use of other tools. The following are the mainstream tools involved in front-end engineering project deployment as follows: 👇

  • Jenkins: A scalable automation server that can be used as a simple CI server with automated build, test, and deployment capabilities
  • Docker: a virtual environment container into which you can package your environment, code, configuration files, etc., and finally publish your application
  • NPM: node. js package management tool, mainly used to manage project dependencies, release
  • Nginx: Can be used as a Web server or load balancing server with high performance and high concurrent connections
  • Pm2: Node process management tool, which can be used to simplify the tedious tasks in many Node application tubes

For more use, read Tree Jam’s The Thing about Front-end Operations and Maintenance Deployment.

Reference: “Front-end Architecture from Starter to Micro Front-end”

Please drink a cup 🍵 remember three even oh ~

1. Remember to give 🌲 sauce a thumbs up after reading oh, there is 👍 motivation

2. Pay attention to the interesting things at the front of the public account, and chat with you about the interesting things at the front

3. Github frontendThings thanks to Star✨