Implementation of webpack code fragmentation

Implementation of webpack code fragmentation

background

One of the most important points in achieving high-performance applications is to allow users to load only necessary resources each time as much as possible. Resources that are not too high in priority should be obtained progressively using technologies such as delayed loading, so as to ensure the first screen speed of the page. Code sharding is a technology unique to the webpck packaging tool. This feature allows the code to be split into specific forms so that users do not have to load all of it at once, but can load it on demand.

CommonsChunkPlugin

Although this plug-in is no longer recommended in webpack4, we still need to understand it. This plug-in can extract the common parts from multiple Chunks. Common module extraction can bring several benefits to several projects:

  • The development process reduces repeated module packaging, which can improve the development speed;
  • Reduce the overall resource size;
  • Properly segmented code can make more effective use of client cache.

The default rule of this plugin is that as long as a module is used by two entry chunks, it will be extracted. For example, as long as a and b use react, react will be extracted. But it still has some shortcomings:

  • A CommonChunkPlugin can only extract one vendor. If we want to extract multiple vendors, we need to configure multiple plugins, which will add a lot of duplicate configuration code.
  • The mainfest we mentioned earlier actually makes the browser load one more resource, which is not friendly to the page rendering speed.
  • Due to some internal design defects, CommonChunkPlugin will destroy the dependencies of modules in the original chunk when extracting common modules, making it difficult to perform further optimizations.

splitChunks

This is a new feature of webpack, which improves the code segmentation feature of CommonChunkPlugin and redesigns and implements it. It is not only more powerful than CommonChunkPlugin, but also simpler and easier to use. The code is as follows

module.exports = {
    entry: './foo.js',
    output: {
        filename: 'foo.js',
        publicPath: '/dist/'
    },
    mode: 'development',
    optimization:
        splitChunks: {
            chunks: 'all',
        }
    }
}

// foo.js
import React from 'react';
import('./bar.js');
document.write('foo.js', React.version);

//bar.js
import react from 'react';
console.log('bar.js', React.version);

The default extraction conditions of splitChunk are:

  • The extracted chunks can be shared or come from the node_modules directory. This one is easy to understand. Modules that are referenced multiple times or are in node_modules tend to be common modules and are more suitable for extraction.
  • The extracted js chunk will have a corresponding size, for example, larger than 30KB. If the size of the CSS chunk is larger than 50KB, this is also relatively easy to understand. If the size of the extracted resource is too small, the optimization effect will be average.
  • During the on-demand loading process, the maximum number of resources requested in parallel is less than or equal to 5. On-demand loading means loading scripts by dynamically inserting script tags. We generally do not want to load too many resources at the same time, because each request has the cost of establishing and releasing the link, so the extraction rules only take effect when there are not many parallel requests.
  • During the first load, the maximum number of resources requested in parallel is less than or equal to 3. This is similar to the previous item, except that the performance requirements are often higher when the page is loaded for the first time, so the default threshold here is also lower.

Configuration

splitChunk: {
    chunks: 'async',
    minSize: {
        javascript: 30000,
        style: 50000,
    },
    maxSize: 0,
    minChunks: 1,
    maxAsyncRequests: 5,
    maxInitialRequests: 3,
    automaticNameDelimiter: '~',
    name: true,
    cacheGroups:
        vendor:
            test: /[\\/]node_modules[\\/]/,
            priority: -10,
        },
        default: {
            minChunks: 2,
            priority: -20,
            reuseExistingChunk: true
        }
    }
}

Matching Pattern
There are three values ​​for chunks: async (default), initial, and all. async only extracts asynchronous chunks, initial only works on the entry chunk, and all enables both modes at the same time (recommended)

Matching conditions
minSize, minChunks, maxAsyncRequests, maxInitialRequests

name
The default is true, which means that the newly generated chunks can be automatically named according to the cacheGroups and scope, and separated by automaticNameDelimiter.

cacheGroup
It can be understood as the rules for separating chunks. By default, there are two rules: vendors and default. vendors
It is used to extract all qualified modules in node_modules, and default is used for modules that are referenced multiple times. You can add or modify these rules. If you want to disable a rule, you can also set it to false. When a module conforms to multiple cacheGroups at the same time, the priority configuration item is used to determine the priority.

Loading resources asynchronously

The main problem that asynchronous resource loading solves is that when there are too many modules and the resource size is too large, some modules that are not used temporarily can be delayed in loading. This way, the resources downloaded by the user when the page is rendered for the first time are as small as possible, and subsequent modules are triggered to load when needed, so this is generally called on-demand loading.
There are two asynchronous loading methods in webpack, import (starting from webapck2) and require.ensure (webapck1). The difference between import and es6 module is that it does not require top-level loading and can be loaded as soon as it is used. Because it is just a simple function call, no further explanation is given here.

Summarize

There are several ways to split code - CommonChunkPlugin or SplitChunks, as well as asynchronous resource loading. With the help of these methods, the resource size can be effectively reduced, while the cache can be better utilized to provide users with a more user-friendly experience.

This is the end of this article about the implementation of webpack code slicing. For more relevant webpack code slicing content, please search 123WORDPRESS.COM's previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Electron-vue uses webpack to package multiple pages of entry files
  • How to debug loader plugin in webpack project
  • 80 lines of code to write a Webpack plugin and publish it to npm
  • Implementation steps for building multi-page programs using Webpack
  • 50 lines of code to implement Webpack component usage statistics
  • webpack -v error solution

<<:  Examples of simple add, delete, modify, and query operations using mysql statements

>>:  Install CentOS7 in VMware (set static IP address) and install mySql database through docker container (super detailed tutorial)

Recommend

Six important selectors in CSS (remember them in three seconds)

From: https://blog.csdn.net/qq_44761243/article/d...

Hbase installation and configuration tutorial under Linux

Table of contents Hbase installation and configur...

JavaScript to implement dynamic digital clock

This article shares the specific code for impleme...

User-centered design

I've been asked a lot lately about an apparen...

Organize the common knowledge points of CocosCreator

Table of contents 1. Scene loading 2. Find Node 1...

Kali Linux Vmware virtual machine installation (illustration and text)

Preparation: 1. Install VMware workstation softwa...

Completely uninstall mysql. Personal test!

Cleanly uninstall MySQL. Personally tested, this ...

How to completely delete and uninstall MySQL in Windows 10

Preface This article introduces a tutorial on how...

Scoring rules of YSlow, a webpage scoring plugin developed by Yahoo

YSlow is a page scoring plug-in developed by Yaho...

In-depth analysis of MySQL database transactions and locks

Table of contents 1. Basic Concepts ACID 3.AutoCo...

Sample code for implementing interface signature with Vue+Springboot

1. Implementation ideas The purpose of interface ...

Detailed explanation of Strict mode in JavaScript

Table of contents Introduction Using Strict mode ...

Docker Compose one-click ELK deployment method implementation

Install Filebeat has completely replaced Logstash...

How to use MyCat to implement MySQL master-slave read-write separation in Linux

Table of contents Linux-Use MyCat to implement My...