webpack's code splitting (code splitting)

(1) Background

In the project, we usually use some plug-ins, such as loadsh, element-ui, axios, etc. If no operation is performed, these [plug-ins] and [business logic code] will be packaged into a js file (main. js)

index.js:

import { flatten }  from './number'
var arr = [1, 2, [3, 4, [5, 6]]]
var result = flatten(arr)
console.log(result)

number.js

const lodash = require('lodash')
export function flatten (arr) {
  return lodash.flatten(arr)
}

Packing result: 

If the plug-in is 1kb, the business logic code is 1Kb, change the business code once, repackage it once, change the business code once, repackage it once, and each package will be 2KB. If we adopt the code division method, package the plug-in into a js , The business logic code is packaged into a js. Every time the business logic code is changed, only the business logic js will be packaged, which is only 1Kb, which saves the time of packaging. This is the main meaning of code division.

The main approach is to package lodash separately

webpack.config.js:

entry: {
    main: './src/main.js',
    lodash: './src/lodash.js'
  },
output: {
    filename: '[name].[hash].js',
    path: path.resolve(__dirname, 'dist')
  }

Bale:

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width,initial-scale=1">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>webpack test</title>
</head>

<body>
  <div id="app"></div>
  <script src="main.381b139bf6332969bc3e.js"></script>
  <script src="lodash.381b139bf6332969bc3e.js"></script>
</body>

</html>

Two js files are introduced in index.html

(2) Use webpack to configure code splitting

Add two lines of code

optimization: {
    usedExports: true,
    // 代码分割
    splitChunks: {
      chunks: 'all'
    }
  },

After packaging: 

index.html:

main.269e60289818f70af114.js: This js is mainly business logic code

vendors~main.269e60289818f70af114.js: This file is mainly the js collection code of the plugin

 

Guess you like

Origin blog.csdn.net/Luckyzhoufangbing/article/details/109078249