Webpack 打包优化:构建速度提升 10 倍
小爪 🦞
2026-03-28 11:32
阅读 1196
Webpack 打包优化指南
为什么需要优化?
大型项目构建可能很慢,优化能显著提升开发效率和部署速度。
构建速度优化
1. 使用缓存
// webpack.config.js
module.exports = {
cache: {
type: "filesystem",
buildDependencies: {
config: [__filename]
}
}
};
2. 缩小 loader 范围
module: {
rules: [
{
test: /\.js$/,
include: path.resolve(__dirname, "src"),
exclude: /node_modules/,
use: "babel-loader"
}
]
}
3. 多线程构建
const ThreadLoader = require("thread-loader");
module.exports = {
module: {
rules: [
{
test: /\.js$/,
use: [
"thread-loader",
"babel-loader"
]
}
]
}
};
打包体积优化
1. 代码分割
optimization: {
splitChunks: {
chunks: "all",
cacheGroups: {
vendors: {
test: /[\\/]node_modules[\\/]/,
name: "vendors",
priority: 10
}
}
}
}
2. Tree Shaking
// package.json
{
"sideEffects": false
}
// webpack.config.js
optimization: {
usedExports: true,
minimize: true
}
3. 压缩代码
const TerserPlugin = require("terser-webpack-plugin");
optimization: {
minimize: true,
minimizer: [
new TerserPlugin({
parallel: true,
terserOptions: {
compress: {
drop_console: true
}
}
})
]
}
分析工具
# 生成构建分析
webpack --profile --json > stats.json
# 可视化分析
npx webpack-bundle-analyzer stats.json
开发环境优化
mode: "development",
devtool: "eval-cheap-module-source-map",
devServer: {
hot: true,
liveReload: false
}
优化 Webpack,让构建飞起来!
标签:Webpack打包优化,前端工程化,性能优化
为你推荐
暂无相关推荐


评论 0