Front-end engineering is essentially a kind of software engineering. Software engineering pays attention to performance, stability, availability, maintainability and other aspects. It pays attention to the basic development efficiency, operation efficiency and maintenance efficiency at the same time. All work towards these goals is “front-end engineering”. Engineering is an idea, not a technology.

In this article you can learn:

  • How to make small programs support SCSS;
  • How to compile your project with Gulp;
  • Module encapsulation commonly used in projects;
  • How the applets interact with the WebView gracefully;
  • Centrally manage your projects to improve maintainability;
  • Improve the development efficiency of the small tool writing;

Full text based on the native small program development described, a variety of third-party framework development is not included. I will not write out the entire construction process of the project in detail, but select some important points in the development process that I think exist in detail.

The common applets development process is likely to encounter pits

List some common ones

  • Small programs themselves do not support the common CSS precompiler, resulting in style specifications scattered in various files, can not be unified management, and modern front-end development whether less,sass,stylus can improve the efficiency of CSS;
  • Lack of uniform request intercepting request;
  • Lack of unified routing management;
  • Lack of centralized API address and ENV environment variable management;
  • Lack of uniform local cache read management;
  • Duplicate WebView pages;
  • Advanced syntax above ES7, such as async await, is not supported.
  • There can only be one environment for either the experience version or the development version, and it is cumbersome to switch between the test environment once the release preview is released;
  • Before going online, you need to manually modify the online environment, which is prone to errors……

How to solve it?

To solve the engineering problem, we need to start from two perspectives: development && deployment.

The development of

Question

  • How to improve development productivity?
  • How to make code maintenance easier?

Program

  • Develop development specifications, improve team cooperation ability;
  • Use automated compilation tools to enable the project to support various plug-ins and efficiency tools;
  • Module/componentized development;
  • All the places that need to be centralized are unified;

The deployment of

  • Environment switching;
  • Compression packaging;

Project structures,

Complete directory structure

The development process

Engineering scheme selection

For the current common engineering solutions, webpack, rollup, parcel, etc., are often used with single-page applications packaging and processing, while small programs are inherently “multi-page applications” and have some specific configurations. Based on the problem to be solved, which is nothing more than compiling, modifying, and copying files, for these requirements, we think that stream-based Gulp is very well suited to handle and is much easier to configure than WebPack for multi-page applications. Therefore, gulp is recommended for small program engineering.

Start

Initializes a project with the following structure

  • srcFor the development directory
  • dist(visible when compiling is enabled) for preview/upload directory
  • .gitignoreGit uploads ignore files
  • gulpfile.jsCompiling a configuration file
  • CHANGELOG.mdVersion Update log
  • README.mdProject description file
  • package.jsonProject configuration file

The compiled plug-ins are installed by NPM or YARN. The installation process is described in detail and you do not need to search for them. “Gulp” : “^ 3.9.1” “gulp – sass” : “^” 4.0.2 SCSS compile the plug-in “gulp – postcss” : “^ 6.4.0” powerful CSS processing plug-in “gulp – rename” : “^1.2.2” Changes file name “gulp-replace”: “^1.0.0” Replace content “gulp-changed”: “^3.2.0” Detects changes “autoprefixer”: “^6.5.1” automatically adds the prefix

How to use SCSS?

WXSS supports style import, but as mentioned above, small programs are inherently multi-page applications, each page has a WXSS, so sass packaging will package the import file into the current file. As a result, the current file size becomes larger. Since wechat limits a single package of code to no more than 2M, this packaging method is bound to make the style file bigger and bigger as more CSS is written.

Solve import problem

Sass does not handle the import part of the statement. Sass does not handle the import part of the statement. There are two ways to do this. The first is to rewrite the source code for sASS processing and skip it when an import statement is encountered. The second option is to comment out the import part of the file before handing it over to sass, so that sass will ignore it, and then open the commented statement when sass is finished. Obviously, the first one costs more and is not easy to maintain, so we use the second one. There is one more thing to note when dealing with imports. In sass, import can not only import CSS, but also variables and functions. Therefore, we need to be careful to distinguish between variables and functions. It is better to have a separate directory for storing variables and functions. When importing variables and functions, you must hand them to sass, which means you cannot comment them out. So we separate configuration sass variable and function to store location, so that we at the time of packaging, import statements like this, we will skip, to sass, or on behalf of its is the introduction of common style file, so we to sass, first it commented out, sass processing after the completion of the open the comments again.

The complete implementation supports SCSS as follows:

  • Specifies the file processing directory
  • Gulp-replace annotates it with a regular match @import statement
  • Determines whether the current @import statement exists in the configuration path of the variable and function files
  • Comment if it doesn’t exist, skip if it does
  • Enable gulp-sass to compile SCSS files.
  • Use PostCSS to handle compatible styles for ios and Android versions
  • Gulp-rename Changes the file name suffix to. WXSS
  • Gulp-replace opens the comment with a regular match with the @import statement
  • Finally, enter it into the dist directory

The following code

Copy the rest of the pages, excluding SCSS files or using gulp-clean to clean unnecessary files

Setting up a monitoring task

Create a default execution task

Throw the generated dist directory as the root directory into the applets development tool to refresh the preview applets in real time. At this point, your project has fully supported SCSS.

Improve the maintainability of your code – encapsulation

Request Requests the interceptor

Wx. Request is the most commonly used API in small programs. In actual projects, there will be many needs to be unified interception/sending/processing. Therefore, we need to carry out secondary encapsulation of WX. Request to support various requirements and achieve code maintainability. The applets themselves already support the promise syntax, and here we use a Promise to wrap it in the common.then form

What to do?

  • Header and data can be used to send common parameters, such as the token requested for authentication, user ID, etc…
  • Can be unified error interception processing, such as global login status judgment, special code code processing…
  • Can adapt request environment according to configuration, such as Mock, Dev, Test, Slave, Prod…

Functions that need to be supported

  • Request way
  • Parameter passing
  • Success callback
  • Failure callback
  • Whether to enable mock data
  • Whether loading is displayed during a request
  • Whether to display toast when requesting an error

Code implementation

Call way


In the app.js entry file, and mount it to the app object, need to call the method of getApp() call

index.js

The Router routing

The encapsulation of routes is mainly to prevent the scattered routing address files from centralized management.

Functions that need to be supported

  • Routes with no parameters and routes with parameters
  • Routing Address abbreviation
  • Parameter passing
  • Jump time delay
  • Jump type

The code implementation defines the object that stores the routing address, which is directly matched by the key value when used

push
path
option
option
Path, Query, Duration, openType

Call way

Stroage storage

Proper Stroage method encapsulation allows you to manage your local cache more gracefully. The three common methods of setItem, getItem, and Clear should be supported. It is also a good idea to have a set of write cache specifications within your team, so that you do not have to do it all at once, and divide the access into modules so that you can better maintain your local cache information.

Code implementation

Write and read both support the common key– >value is compatible with key– >value– >module module mode, the default use synchronous mode Settings, catch is added to prevent in special cases small program will alarm set cache error, such as synchronous error is used asynchronous tolerance. SetItem Write cache

getItem

clear

Call way


API address and ENV environment variable management

ENV stores multiple environment variables. Configure the current environment domain names in the environment object. Then configure the current environment variable in app.js to match the environment in ENV as a key value, and mount the app object to the matching environment. With the fetchApi package in front of the env+ URL to achieve automatic environment adaptation.

API

ENV

app.js

The unity of the webview

Wechat applet provides the ability to embed HTML pages in applet. Starting from the wechat applet base library 1.6.4, you can place a component within the applet to link HTML pages. With it can be convenient to several end of the common H5 page integration into the small program, for us to reduce the considerable workload.

If you have multiple WebView pages that need to be integrated, you don’t actually need to create a separate file for each page. Simply encapsulate and route a common WebView page to centrally manage your WebView pages.

Code implementation

WXML introduces the WebView component and the loading animation, the WebView component receives the address, and the loading success callback.

How to solve the problem of switching between multiple environments

Small program unlike h5 web page as long as the deployment to the corresponding environment, can be arbitrary input specified domain testing environment, and this small program like app url, it will only have a preview, normal process is every time when students need in different environments testing students manual changes will need to find the development environment and redistribute the experience. This process is very inflexible, so we need to find a way to let a small version of a program freely switch between multiple environments without having to manually change the code configuration distribution. How? There are many ways to achieve the idea, the main need to solve is how to switch the environment, here I use the small program gravity induction API simulation shake, the switch environment into a hidden small eggs, The tester just needs to shake the pop-up environment option list and click the option to change the env environment attribute in the Config of the App object to successfully switch the environment.

Code implementation

How do I automatically package the deployment environment to prevent error prone manual configuration

In this case, we need to use gulp to package the code in different environments. It is easy to configure. The only way to do this is to configure app.js environment variables in gulp-replace. But to cooperate with the micro channel development tools of the custom processing command every time in the release of the version of the audit only need to open the function.

gulpfile.js

project.config.json

Developer tools

The above list of common engineering solutions in the development process, and hope to have a reference for everyone, if there is a problem welcome correction.