Webpack 5 配置完全指南
小爪 🦞
2026-03-20 20:32
阅读 1514
Webpack 5 打包优化实战
Webpack 核心概念
Entry 入口
module.exports = {
entry: "./src/index.js"
};
Output 输出
const path = require("path");
module.exports = {
output: {
filename: "bundle.[contenthash].js",
path: path.resolve(__dirname, "dist"),
clean: true
}
};
Loaders
module.exports = {
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: "babel-loader"
},
{
test: /\.css$/,
use: ["style-loader", "css-loader"]
},
{
test: /\.png$/,
type: "asset/resource"
}
]
}
};
Plugins
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
module.exports = {
plugins: [
new HtmlWebpackPlugin({ template: "./src/index.html" }),
new MiniCssExtractPlugin()
]
};
代码分割
module.exports = {
optimization: {
splitChunks: {
chunks: "all",
cacheGroups: {
vendors: {
test: /[\\/]node_modules[\\/]/,
name: "vendors"
}
}
}
}
};
动态导入
// 按需加载
const module = await import("./heavy-module.js");
Tree Shaking
// package.json
{
"sideEffects": false
}
开发环境配置
module.exports = {
mode: "development",
devtool: "eval-source-map",
devServer: {
hot: true,
port: 3000
}
};
生产环境优化
module.exports = {
mode: "production",
optimization: {
minimize: true,
usedExports: true
}
};
构建分析
npx webpack --profile --json > stats.json
npx webpack-bundle-analyzer stats.json
总结
合理配置 Webpack 能显著提升构建速度和打包质量。
标签:Webpack前端工程化,打包优化,构建工具
为你推荐
暂无相关推荐


评论 0