webpack代码分割(https://webpack.js.org/guides/code-splitting/)

本文详细介绍了webpack的代码分割特性,包括手动分割、防止重复和动态引入,并提供了配置示例。通过代码分割,可以实现按需加载和并行加载,从而减少加载时间。动态引入的两种方法分别是使用es6的import和require.ensure。最后提到了分析bundle的重要性及可用的分析工具。

Code Splitting代码分割

 

代码分割是webpack最令人信服的特性,这个特性允许你将代码分割为不同的部分,然后按需加载或者并行加载。它可以用于获得更小的打包文件、按照加载优先级控制资源,进而减少加载时间。(将原先集中到一个 output.js 中的代码,切割成若干个 js 文件,然后分别进行加载。原先只加载 output.js ,现在把代码分割到3个文件中,先加载 output.js ,然后 output.js 又会自动加载 1.output.js 和 2.output.js 。)

有3个代码分割的通用方法

》入口点:利用entry配置手动进行代码分割

》杜绝重复:利用CommonsChunkPlugin插件删除重复的代码、分割chunks代码

》动态引入: Split code via inline function calls within modules.

 

 一、利用entry手动分割

 

webpack.config.js


 
const path = require('path');
const HTMLWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  entry: {
    index: './src/index.js',
    another: './src/another-module.js'
  },
  plugins: [
    new HTMLWebpackPlugin({
      title: 'Code Splitting'
    })
  ],
  output: {
    filename: '[name].bundle.js',
    path: path.resolve(__dirname, 'dist')
  }
};

这种方法的缺点是:

1.分割后的压缩文件会包含重复的代码

2.不灵活,无法动态分割代码

 

 

二、Prevent Duplication

 

利用commonChunkPlugin插件会从各个出口文件中提取出公有的代码,例子如下:

webpack.config.js

  const path = require('path');
+ const webpack = require('webpack');
  const HTMLWebpackPlugin = require('html-webpack-plugin');

  module.exports = {
    entry: {
      index: './src/index.js',
      another: './src/another-module.js'
    },
    plugins: [
      new HTMLWebpackPlugin({
        title: 'Code Splitting'
-     })
+     }),
+     new webpack.optimize.CommonsChunkPlugin({
+       name: 'common' // Specify the common bundle's name.
+     })
    ],
    output: {
      filename: '[name].bundle.js',
      path: path.resolve(__dirname, 'dist')
    }
  };

 

利用commonChunkPlugin插件,我们可以看到重复的代码从index.bundle.js中被移除,而在asset那一栏,多了一个common.bundle.js文件,这些是提取出的公有的代码。

 

Hash: 70a59f8d46ff12575481
Version: webpack 2.6.1
Time: 510ms
            Asset       Size  Chunks                    Chunk Names
  index.bundle.js  665 bytes       0  [emitted]         index
another.bundle.js  537 bytes       1  [emitted]         another
 common.bundle.js     547 kB       2  [emitted]  [big]  common
   [0] ./~/lodash/lodash.js 540 kB {2} [built]
   [1] (webpack)/buildin/global.js 509 bytes {2} [built]
   [2] (webpack)/buildin/module.js 517 bytes {2} [built]
   [3] ./src/another-module.js 87 bytes {1} [built]
   [4] ./src/index.js 216 bytes {0} [built]

 

 

三、动态引入

 

webpack支持2种动态代码分割的方法,第一种也是比较好的一种方法是使用es6的import特性,特定于webpack的方法是使用require.ensure特性,让我们首先演示第一种方法。

import使用了promise,所以,如果你想在缺少promise支持的浏览器上啊运行,需要引入promise polyfill

 

webpack.config.js

 

  const path = require('path');
- const webpack = require('webpack');
  const HTMLWebpackPlugin = require('html-webpack-plugin');

  module.exports = {
    entry: {
+     index: './src/index.js'
-     index: './src/index.js',
-     another: './src/another-module.js'
    },
    plugins: [
      new HTMLWebpackPlugin({
        title: 'Code Splitting'
-     }),
+     })
-     new webpack.optimize.CommonsChunkPlugin({
-       name: 'common' // Specify the common bundle's name.
-     })
    ],
    output: {
      filename: '[name].bundle.js',
+     chunkFilename: '[name].bundle.js',
      path: path.resolve(__dirname, 'dist')
    }
  };

chunkFilename,指的是给没有对应入口文件的出口文件命名。

index.js

function getComponent(){
    return import('lodash').then(_ => {
        var element = document.createElement('div');
        element.innerHTML = _.join(['hello','webpack'],' ');
        return element;
    }).catch(error => 'an error occured while loading the component');
}

getComponent().then(component => {
    document.body.appendChild(component);
})

构建后的结果为:

由上图可以看出:dist中有2个js文件,其中app1.bundle.js是index.html中引入的文件,0.bundle.js是app1.bundle.js依赖的文件,其在运行时动态加载。通过这种引入方式,加快了页面执行的速度。

 

Bundle Analysis

 

一旦你开始切割你的代码后,分析输出文件,判断文件是从哪个模块切分的,是非常重要的,最好从官方的分析工具开始入手。当然,也可以选择如下工具:

webpack-chart,    webpack-visualizer   webpack-bundle-analyzer

 

PS E:\soft\finnal\yuanma2\crm1> npm run build:portable > crm1@0.1.0 build:portable > vue-cli-service build --modern && electron-builder --win portable Browserslist: caniuse-lite is outdated. Please run: npx update-browserslist-db@latest Why you should do it regularly: https://github.com/browserslist/update-db#readme All browser targets in the browserslist configuration have supported ES module. Therefore we don't build two separate bundles for differential loading. ⠇ Building for production...Browserslist: caniuse-lite is outdated. Please run: npx update-browserslist-db@latest Why you should do it regularly: https://github.com/browserslist/update-db#readme ⠋ Building for production...Browserslist: caniuse-lite is outdated. Please run: npx update-browserslist-db@latest Why you should do it regularly: https://github.com/browserslist/update-db#readme Browserslist: caniuse-lite is outdated. Please run: npx update-browserslist-db@latest Why you should do it regularly: https://github.com/browserslist/update-db#readme Browserslist: caniuse-lite is outdated. Please run: npx update-browserslist-db@latest Why you should do it regularly: https://github.com/browserslist/update-db#readme ⠙ Building for production...Browserslist: caniuse-lite is outdated. Please run: npx update-browserslist-db@latest Why you should do it regularly: https://github.com/browserslist/update-db#readme ⠹ Building for production...Browserslist: caniuse-lite is outdated. Please run: npx update-browserslist-db@latest Why you should do it regularly: https://github.com/browserslist/update-db#readme ⠼ Building for production...Browserslist: caniuse-lite is outdated. Please run: npx update-browserslist-db@latest Why you should do it regularly: https://github.com/browserslist/update-db#readme ⠹ Building for production...Browserslist: caniuse-lite is outdated. Please run: npx update-browserslist-db@latest Why you should do it regularly: https://github.com/browserslist/update-db#readme Browserslist: caniuse-lite is outdated. Please run: npx update-browserslist-db@latest Why you should do it regularly: https://github.com/browserslist/update-db#readme ⠙ Building for production... WARNING Compiled with 4 warnings 08:31:03 warning /js/chunk-vendors.1a0a0613.js is 2.28 MB, and won't be precached. Configure maximumFileSizeToCacheInBytes to change this limit. warning asset size limit: The following asset(s) exceed the recommended size limit (244 KiB). This can impact web performance. Assets: img/0001.bbc23d94.jpg (1.85 MiB) css/chunk-vendors.7d75f85b.css (306 KiB) js/chunk-vendors.1a0a0613.js (2.17 MiB) warning entrypoint size limit: The following entrypoint(s) combined asset size exceeds the recommended limit (244 KiB). This can impact web performance. Entrypoints: app (2.6 MiB) css/chunk-vendors.7d75f85b.css js/chunk-vendors.1a0a0613.js css/app.e3c96718.css js/app.22cb88f3.js warning webpack performance recommendations: You can limit the size of your bundles by using import() or require.ensure to lazy load some parts of your application. For more info visit https://webpack.js.org/guides/code-splitting/ File Size Gzipped dist\js\chunk-vendors.1a0a0613.js 2222.03 KiB 687.66 KiB dist\js\app.22cb88f3.js 130.49 KiB 17.91 KiB dist\workbox-5b385ed2.js 14.11 KiB 4.93 KiB dist\service-worker.js 1.20 KiB 0.76 KiB dist\css\chunk-vendors.7d75f85b.css 305.86 KiB 42.07 KiB dist\css\app.e3c96718.css 1.40 KiB 0.63 KiB Images and other types of assets omitted. Build at: 2025-07-03T00:31:03.176Z - Hash: 9fc57e568ce674b2 - Time: 40125ms DONE Build complete. The dist directory is ready to be deployed. INFO Check out deployment instructions at https://cli.vuejs.org/guide/deployment.html • electron-builder version=26.0.12 os=10.0.19041 • description is missed in the package.json appPackageFile=E:\soft\finnal\yuanma2\crm1\package.json • author is missed in the package.json appPackageFile=E:\soft\finnal\yuanma2\crm1\package.json • writing effective config file=dist\builder-effective-config.yaml • executing @electron/rebuild electronVersion=37.2.0 arch=x64 buildFromSource=false appDir=./ • installing native dependencies arch=x64 • completed installing native dependencies • packaging platform=win32 arch=x64 electron=37.2.0 appOutDir=dist\win-unpacked
07-04
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值