Author: Tian Yin

Front-end resource packaging is a part of every project, and every developer wants packaging to build the least amount of code in the least amount of time. This not only improves productivity on the team, but also improves page access performance. Here are some ways to optimize build speed and build output code.

Image from webpack official website log

1. Speed optimization

Daily development package configuration we are used to scaffolding and other default configuration, no problem, no problem, run well, do not care so much. For some obsessive-compulsive patients, there is still a bit of discomfort, such as speed, such as the size of the final package of resources and so on.

1.1 Local Build or Server Build

1.1.1 Local Build

Once developed, build locally and then synchronize resources by pushing them to CND. May be the traditional way of thinking we like to do, no problem, but also very good use.
Disadvantages: Increased warehouse size, and local builds do not enjoy real-time package updates for semantic NPM packages in the repository.
Advantages: Suitable for the early stage of multi-party project collaboration, or depending on a three-party package is also in an iterative process, each person in the process of development only packaging their own pages, not interfering with each other

1.1.2 Server Construction

Server-side builds, roughly when resources are pushed, run ci-like services on a build machine, as well as packaged services
Advantages and disadvantages are basically the opposite of the local, but still more recommended such a scheme

1.2 How to optimize

1.2.1 Configuration Differences

In fact, you might expect this configuration to be automated, and you can only do one copy. The idea is correct, but you should make some distinctions
function
Local development
Posted online
The compression code
Need to be
babel-polyfill
Usually not
Look at business requirements
The separation of style
Need to be
Remove the console log
Need to be
css Prefix
Need to be
OccurrenceOrderPlugin
Need to be
DedupePlugin
Need to be
Babel present transcoding
Need to be

Setting environment variables for Windows compatibility can be done using cross-env
The above comparison was not tested, but if you are interested, you can try to see how many optimizations you can make on the old basis.
To sum up, local development is about speed and less processing

1.2.2 Common Methods

You can see a lot of articles in the community about how to optimize webpack, all kinds of speed up, you probably know, but don’t bother to do it, but actually once it’s done, the benefits are huge.
externals
Extern: This is probably one of the most violent and fast ways to get extern functions out of the way. If extern is extern, it is also a good idea to get rid of the related react-addons-transition-groups, React-addons-transition-group package contains code similar to the following. Externals cannot be excluded
module.exports = require('react/lib/ReactTransitionGroup');Copy the code
Dll
Some predictable libraries can be extracted and pre-packaged, which can greatly improve the speed. At that time, there are still a lot of things to pay attention to. For example, the same package had better have only one copy globally, and pre-packaged can not enjoy the semantic version of resources and new, which needs to be combined with practical problems to see whether it is needed.
HappyPack
Acceleration of common routine
const os = require('os');

HappyPack.ThreadPool({size: os.cpus().length })Copy the code
Some configuration
Set some aliases and exclude some loaders
Set the csS-Loader version
The speed increase is particularly noticeable
"CSS - loader", "^ 0.14.5",Copy the code
Related Issue
Replace SCSS-loader with fast-sas-loader
In comparison, it is faster than SCSS-Loader
Don’t use the uglfiyJS that comes with WebPack
It’s slower to compress with uglfiyJS, so there’s two ideas here, but the principle should be the same
  1. webpack-uglify-parallel
  2. Build a new wheel multi-core parallel compression js and CSS
This scheme optimization generally increases the speed by about half
Separation of JS and SCSS
This can optimize the rebuild speed in the local development process, and try to separate THE SCSS file from the JS file. If you use some UI libraries, you can reference the CSS file of the UI library instead of the SCSS file, saving the SCSS build process every time

1.3 other

  1. Webpack can be a full-featured tool, and there are many other tools like rollup or Browserify, depending on the specific scenario, it may be better to choose a more appropriate knife, rather than blindly choose to use a knife. Some other packaging schemes will be added in detail after subsequent attempts.
  2. Optimization never ends

2. Code optimization

2.1 streamline node_modules

At present, the development basically uses NPM or YARns for dependency management, and the random introduction of several dependencies will make the final package structure bloated. In addition, the developer may not have a particular unified management of dependent packages, and will introduce what is needed without caring about the relationship between each other.

The figure above is just a very graphic illustration of the amount of packages available when node_modules is managed. What’s Really Wrong with Node_modules and Why this is your fault
Note: NPM package developers should ensure that the package contains only the required code, such as testing resources should be ignored, which can also save a lot of money, details will be sorted out in a new article.

2.1.1 Method 1: Use the same package for the same function

It’s common for multiple developers to use tripartite libraries, some of them using deep-extend, but later on, some of them using LoDash, which can cause multiple references to the same package over and over again. This doesn’t cause bugs, but it does cause node_modules to grow and package.json dependencies to become messy, as well as a loss of code size.
The solution
Look at the warehouse’s package.json, for example
{" deep - the extend ", "^ 0.4.1", "lodash. Clonedeep" : "^ 4.5.0",}Copy the code
The above two libraries are to do deep copy, you can choose to use only one, recommended

2.1.2 Method 2: Avoid multiple versions of the same package

In most cases this only increases the size of the code, etc., but in a few cases, such as using a front-end component library;
For example, the project relies on two components A and B. A relies on the 1.0.0 input of A UI library C, while B relies on the 2.0.0 input of C. The final page will have both versions of the input. This time whether the use of 1.0.0 or 2.0.0 style is not appropriate), so this problem also needs more attention, especially the front-end UI library, the best habitual investigation is better. You’d better do it
The solution
Open chrome debug tool, check node_modules, for UI library, carefully browse, can not have multiple versions of the library, for other libraries can be budded check; If you find A library A appearing multiple times, you can use NPM ls A to see where it is referenced multiple times, and then navigate to the detailed package

2.1.3 Approach 3: Analyze code dependencies

If webpack is used, BundleAnalyzerPlugin or its own function is used to output JSON for analysis and check why the final output resources are so large

2.2 Remove public Resources

More suitable for the development of the whole site, the common resources of each page out, so that in the process of accessing the page browser can be a good cache of these general resources, similar to the use of DLL exists in the local project, but also can make packaging speed, the following DLL as an example
practice
  1. Configure the project to play DLL resources, the general choice is some tripartite libraries, see the specific needs of the project
  2. Pre-typed DLL resources are placed in a custom directory of the project (you can even type the production version directly to avoid subsequent compression)
  3. After the local build or server build task is complete, copy the prepared DLL resources to the build directory
Pay attention to the point
  1. If you use the server build, make sure that the local NPM version is the same as the server build version. Different NPM versions may cause the contents of the manifest.json to be inconsistent because the DLL is stored in the path
  2. It is better to solve the problem of multiple versions of the same library, otherwise the DLL will be typed into multiple versions of the library, because the DLL store path of different versions of the version number is inconsistent

2.3 other

2.3.1 use Babel – preset – env

It is also recommended to replace Babel-preset -2015. Choose the right one based on the browser the service needs. Otherwise, redundant transcoding makes the code become larger after transcoding

2.3.2 The problem of distinguishing between large packages and small packages

Some component libraries or LoDash
import { isEmpty } from 'lodash';

import isEmpty from 'lodash/isEmpty';Copy the code
The results are different. Unless supported by a transcoding tool; Vscode users suggest installing an Import Cost

2.3.3 Upgrading the WebPack Tool

Upgrade to Webpack3, tree Shaking, Scope collieries all have good code optimization

2.3.4 Optimize styles

  1. PostCss handles prefix tasks according to service requirements, no more or less
  2. Simplify styles and eliminate unnecessary styles