代码分离是 webpack 中最引人注目的特性之一。此特性能够把代码分离到不同的 bundle 中,然后可以按需加载或并行加载这些文件。代码分离可以用于获取更小的 bundle,以及控制资源加载优先级,如果使用合理,会极大影响加载时间。
常用的代码分离方法有三种:
- 入口起点:使用 entry 配置手动地分离代码。
- 防止重复:使用 Entry dependencies 或者 SplitChunksPlugin 去重和分离 chunk。
- 动态导入:通过模块的内联函数调用来分离代码。
1.8.1 入口起点
这是迄今为止最简单直观的分离代码的方式。不过,这种方式手动配置较多,并有一些隐患,我们将会解决这些问题。先来看看如何从 main bundle 中分离 another module(另一个模块):
在 src目录下创建 another-module.js文件:
09-code-splitting/src/another-module.js
import _ from 'lodash'
console.log(_.join(['Another', 'module', 'loaded!'], ' '))
这个模块依赖了 lodash,需要安装一下:
[felix] webpack5 $ npm install lodash --save-dev
修改配置文件:
module.exports = {
entry: {
index: './src/index.js',
another: './src/another-module.js',
},
output: {
filename: '[name].bundle.js'
},
}
09-code-splitting/webpack.config.js
//...
module.exports = {
entry: {
index: './src/index.js',
another: './src/another-module.js',
},
output: {
filename: '[name].bundle.js'
//...
},
//...
}
执行编译:
[felix] 09-code-splitting $ npx webpack
assets by status 744 KiB [cached] 4 assets
assets by status 1.44 MiB [emitted]
asset another.bundle.js 1.38 MiB [emitted] (name: another)
asset index.bundle.js 65.1 KiB [emitted] (name: index)
asset app.html 441 bytes [emitted]
Entrypoint index 68.9 KiB (740 KiB) = styles/4a9cff551c7a105e1554.css 3.81 KiB index.bundle.js 65.1 KiB 3 auxiliary assets
Entrypoint another 1.38 MiB = another.bundle.js
runtime modules 3.23 KiB 12 modules
cacheable modules 549 KiB (javascript) 738 KiB (asset) 2.65 KiB (css/mini-extract)
javascript modules 546 KiB
modules by path ../node_modules/ 540 KiB 9 modules
modules by path ./src/ 5.48 KiB 8 modules
asset modules 3.1 KiB (javascript) 738 KiB (asset)
./src/assets/img-1.png 42 bytes (javascript) 101 KiB (asset) [built] [code generated]
./src/assets/webpack-logo.svg 2.99 KiB [built] [code generated]
./src/assets/example.txt 25 bytes [built] [code generated]
./src/assets/qianfeng-sem.jpg 42 bytes (javascript) 637 KiB (asset) [built] [code generated]
json modules 565 bytes
./src/assets/json/data.toml 188 bytes [built] [code generated]
./src/assets/json/data.yaml 188 bytes [built] [code generated]
./src/assets/json/data.json5 189 bytes [built] [code generated]
css ../node_modules/css-loader/dist/cjs.js!./src/style.css 2.65 KiB [built] [code generated]
webpack 5.54.0 compiled successfully in 854 ms
asset another.bundle.js 1.38 MiB [emitted] (name: another) , 我们发现 lodash.js也被打包到 another.bundle.js 中。
查看 app.html:
09-code-splitting/dist/app
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>千锋大前端教研院-Webpack5学习指南</title>
<link href="styles/4a9cff551c7a105e1554.css" rel="stylesheet">
</head>
<body>
<script defer src="index.bundle.js"></script>
<script defer src="another.bundle.js"></script>
</body>
</html>