手动分包是一种优化 Webpack 打包过程的方法,特别是在处理大型项目或第三方库时。通过预先打包公共模块并生成资源清单(manifest),Webpack 可以在后续的构建过程中跳过这些公共模块的重新打包,从而提高构建速度和减少最终打包文件的体积。
以下是详细的步骤和配置示例,帮助你实现手动分包。
1. 打包公共模块
首先,你需要创建一个独立的 Webpack 配置文件来单独打包公共模块,并使用 DllPlugin 生成资源清单。公共模块会被打包成为动态链接库(dll Dynamic Link Library),并生成资源清单
创建 webpack.dll.config.js
const path = require('path');
const webpack = require('webpack');
module.exports = {
mode: 'production',
entry: {
vendor: ['jquery', 'lodash'] // 将需要分离的库放在同一个入口中
},
output: {
filename: 'dll/[name].js',
path: path.resolve(__dirname, 'dist'),
library: '[name]' // 暴露全局变量名
},
plugins: [
new webpack.DllPlugin({
path: path.resolve(__dirname, 'dist', 'dll', '[name].manifest.json'), // 资源清单保存位置
name: '[name]', // 资源清单中暴露的变量名
context: __dirname // 上下文路径,必须与主配置中的context一致
})
]
};
2. 使用公共模块
接下来,在你的主 Webpack 配置文件中使用 DllReferencePlugin 来引用这些资源清单,并确保在 HTML 文件中手动引入生成的 DLL 文件。
修改 webpack.config.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin').CleanWebpackPlugin;
const webpack = require('webpack');
module.exports = {
mode: 'development',
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
},
devtool: 'source-map',
module: {
rules: [
{
test: /\.css$/,
use: ['style-loader', 'css-loader']
}
]
},
plugins: [
new HtmlWebpackPlugin({
template: './src/index.html'
}),
new CleanWebpackPlugin({
cleanOnceBeforeBuildPatterns: ['**/*', '!dll', '!dll/**/*'] // 排除dll目录及其内容
}),
new webpack.DllReferencePlugin({
manifest: require('./dist/dll/vendor.manifest.json') // 引用资源清单
})
]
};
3. 在 HTML 文件中引入 DLL 文件
确保在 index.html 中手动引入生成的 DLL 文件,以便浏览器加载这些公共模块。
修改 src/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="root"></div>
<!-- 手动引入DLL文件 -->
<script src="./dll/vendor.js"></script>
</body>
</html>
4. 运行命令
首先运行 webpack --config webpack.dll.config.js 来打包公共模块,然后运行 webpack 或 webpack-dev-server 来打包应用代码。
# 打包公共模块
npx webpack --config webpack.dll.config.js
# 打包应用代码
npx webpack
或者使用 webpack-dev-server:
# 启动开发服务器
npx webpack serve
总结
手动打包的过程:
- 开启
output.library暴露公共模块 - 用
DllPlugin创建资源清单 - 用
DllReferencePlugin使用资源清单
手动打包的注意事项:
- 资源清单不参与运行,可以不放到打包目录中
- 记得手动引入公共JS,以及避免被删除
- 不要对小型的公共JS库使用
优点:
- 极大提升自身模块的打包速度
- 极大的缩小了自身文件体积
- 有利于浏览器缓存第三方库的公共代码
缺点:
- 使用非常繁琐
- 如果第三方库中包含重复代码,则效果不太理想