Webpack version: 4.35.0

Webpack – CLI version: 3.3.5

Why do we need code splitting

In current front-end projects, it is common to compress multiple files into one using gulp, Webpack, Browserify, and so on. This process is called packaging. Packaging is the process of bringing in and merging files into a single file, eventually forming a “bundle.” The bundle is then introduced on the page and the entire application is loaded at once.

Packaging is a great technique, but as your application grows, so will your code package. This is especially true if you integrate large third-party libraries. You need to pay attention to the code contained in your code package so that it does not take too long to load because it is too large.

To avoid large packages, it’s a good idea to think about them upfront and split them up. Code splitting is a technique supported by packers such as Webpack (code splitting) and Browserify (fact-Bundle), enabling multiple packages to be created and loaded dynamically at run time.

Breaking up your app’s code helps you lazily load what your current users want, which can significantly improve your app’s performance. While it doesn’t reduce the overall code volume of your application, you can avoid loading code that users never need, and reduce the amount of code that needs to be loaded during initial loading.

The key point

Packaging solves the problem of too many dependent files in a project, resulting in too many HTTP requests

Code splitting is a solution to the side effect of packaging — single files that are too large and take too long to load.

Therefore, the key point of code segmentation is how to control the segmentation granularity:

  • How many files to split
  • The file size

Segmentation method

There are three common ways to separate code:

  • Entry point: UseentryConfigure manual separation of code.
  • Dynamic import: Separation of code through inline function calls to modules.
  • Manually detach using plug-ins

entry

Each entry outputs a corresponding file in the final package. So code splitting can be done explicitly:

module.exports = {
    entry: {
        app: './src/index.js'.print: './src/print.js'
    },
    // ...
    output: {
        filename: '[name].[chunkhash].js'.path: path.resolve(__dirname, './dist')}}Copy the code

The package builds will output in the dist folder:

app.f7badf83cc90de106d41.js
print.e00bba994e917cc7fc59.js
Copy the code

Dynamic import

Dynamic import can also achieve the effect of code segmentation:

import _ from 'lodash';

function component() {
  var element = document.createElement('div');

  // Lodash (currently introduced via a script script) is required to perform this line
  element.innerHTML = _.join(['Hello'.'webpack'].' ');

  element.onclick = (e) = > import(/* webpackChunkName: "print" */ './print').then((Print) = >{})return element;
}

document.body.appendChild(component());

Copy the code

WebpackChunkName Sets the name of the output package.

module.exports = {
    entry: {
        app: './src/index.js'
    },
    // ...
    output: {
        filename: '[name].[chunkhash].js'.chunkFilename: '[name].[chunkhash].js'.path: path.resolve(__dirname, './dist')}}Copy the code

The chunkFilename of the output determines the name of the non-entry chunk file. Here the chunk is generated by code splitting, so this option is used to set the name of the file.

Run packaging:

app.73efde30ee057cb8c817.js
print.e4408db3b4e5072295de.js
Copy the code

The plug-in

CommonsChunkPlugin

Prior to WebPack 4, the CommonsChunkPlugin was used for common chunk extraction.

module.exports = {
    entry: './src/index.js'.entry: {
      main: './src/index.js'.vendor: [
        'lodash']},plugins: [
    new CleanWebpackPlugin(['dist']),
    new HtmlWebpackPlugin({
      title: 'Caching'
    }),
      new webpack.optimize.CommonsChunkPlugin({
        name: 'vendor'
      }),
    new webpack.optimize.CommonsChunkPlugin({
      name: 'manifest'})].output: {
    filename: '[name].[chunkhash].js'.path: path.resolve(__dirname, 'dist')}};Copy the code

There are two things worth noting here:

  • entryIn thevendor: Explicit referencelodashBecause ofindex.jsAlso importlodash, so it becomes a public module.
  • usenew webpack.optimize.CommonsChunkPluginExtract these public modules

SplitChunksPlugin

After Webpack 4 CommonsChunkPlugin was deprecated and SplitChunksPlugin was used instead. SplitChunksPlugin is out of the box and only needs to be configured in Module.exports:

module.exports = {
  / /...
  optimization: {
    splitChunks: { // This option will be used to configure SplitChunksPlugin plug-in
      cacheGroups: {
        vendors: {
          test: /[\\/]node_modules[\\/]/.name: 'vendor'.chunks: 'initial'.minChunks: 2}}}},output: {
    filename: '[name].[chunkhash].js'.chunkFilename: '[name].[chunkhash].js'.path: path.resolve(__dirname, './dist')}};Copy the code

The configuration above packs all modules referenced under node_modules into the dist folder using vendor as the chunk name in the output chunkFilename format.

SplitChunksPlugin option:

Each item in a cacheGroups accepts the following parameters:

  • Filename: rewrites the chunk naming mode

    vendors: {
      test: /[\\/]node_modules[\\/]/.name: 'vendor'.filename:'[name].bundle.js'
      chunks: 'initial'.minChunks: 2,}Copy the code

    Finally, a file named vendor.bundle.js is generated

    For the configuration of SplitChunksPlugin, see SplitChunksPlugin Parsing

Divide content

The key to code segmentation is to control the granularity of segmentation:

  • How many files to split
  • The file size

Regardless of size, you end up packing up a single file containing all the code. We can optimization. SplitChunks. MaxSize to control the size of the chunk to achieve the goal of divided into multiple files.

Controlling code splitting by size alone has the following drawbacks:

  • The entry file size is not optimized for maximum

  • Caches cannot be used.

    Some of the tools introduced in the project are updated very infrequently

  • Presentation and structure are not separated.

    When browsers render, presentation and structure are parsed based on different algorithms. Also, the style code increases the response time to the request.

Three party libraries

In projects, it is common to introduce some tripartite tool libraries or polyfills, such as Lodash and Babel-Polyfill. This code changes very little in the project, so it is recommended that you extract it into a separate file.

This has several benefits:

  • You can cache it
  • Optimize entry file size
  • Separation of concerns

CSS

The ExtractTextWebpackPlugin can be used in a project to extract CSS files into separate bundles.


entry: {
    polyfill: './src/utils/polyfill.js'.main: './src/main.js'.app: './src/index.js'
},



Copy the code

Refer to the link

  • The separation

  • The cache

  • Loading polyfills –

  • ExtractTextWebpackPlugin