本文最后更新于 46 天前,其中的信息可能已经有所发展或是发生改变。
🌟 Webpack 5 核心优势
+ 模块联邦实现微前端架构
+ 持久缓存提速构建80%+
+ 改进的Tree Shaking算法
+ 原生支持WebAssembly
- 相比Webpack4配置简化30%
🚀 5分钟基础配置
1. 初始化项目
mkdir webpack-demo && cd webpack-demo
npm init -y
npm install webpack webpack-cli --save-dev
2. 基础配置文件
// webpack.config.js
const path = require('path')
module.exports = {
entry: './src/index.js',
output: {
filename: 'bundle.[contenthash].js',
path: path.resolve(__dirname, 'dist')
},
mode: process.env.NODE_ENV || 'development'
}
3. 添加构建脚本
jsonCopy Code{
"scripts": {
"build": "NODE_ENV=production webpack",
"dev": "webpack serve --open"
}
}
🔥 核心配置解析
1. 加载器配置模板
module: {
rules: [
{
test: /.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env']
}
}
},
{
test: /.scss$/,
use: ['style-loader', 'css-loader', 'sass-loader']
}
]
}
2. 常用插件配置
const HtmlWebpackPlugin = require('html-webpack-plugin')
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
plugins: [
new HtmlWebpackPlugin({
template: './public/index.html'
}),
new CleanWebpackPlugin(),
new webpack.ProgressPlugin()
]
🛠️ 企业级优化方案
1. 代码分割策略
optimization: {
splitChunks: {
chunks: 'all',
cacheGroups: {
vendors: {
test: /[\/]node_modules[\/]/,
priority: -10
}
}
}
}
2. 性能优化矩阵
优化方向 |
实现方案 |
效果提升 |
构建速度 |
cache: { type: ‘filesystem’ } |
二次构建提速70% |
产物体积 |
ImageMinimizerPlugin压缩图片 |
体积减少40% |
首屏加载 |
PreloadWebpackPlugin预加载 |
LCP提升30% |
开发体验 |
webpack-dev-server HMR |
热更新速度提升3x |
💡 高级功能实战
1. 模块联邦配置
// app1/webpack.config.js
new ModuleFederationPlugin({
name: 'app1',
filename: 'remoteEntry.js',
exposes: {
'./Button': './src/components/Button.js'
}
})
// app2/webpack.config.js
new ModuleFederationPlugin({
remotes: {
app1: 'app1@http://localhost:3001/remoteEntry.js'
}
})
2. 自定义Loader示例
// markdown-loader.js
module.exports = function(source) {
return `
export default ${JSON.stringify({
html: marked.parse(source),
meta: frontmatter.parse(source)
})}
`
}
⚠️ 常见问题指南
1. 路径解析问题
// 解决方案
resolve: {
extensions: ['.js', '.jsx', '.json'],
alias: {
'@': path.resolve(__dirname, 'src/')
}
}
2. 环境变量注入
const dotenv = require('dotenv-webpack')
plugins: [
new dotenv({
path: './.env.production'
})
]
3. 构建内存溢出
# 解决方案
node --max-old-space-size=4096 node_modules/webpack/bin/webpack.js
🔄 Webpack vs Vite 对比指南
特性 |
Webpack |
Vite |
构建机制 |
基于Bundle |
原生ESM |
冷启动速度 |
较慢(大型项目) |
极快 |
生态插件 |
极其丰富 |
快速成长中 |
适用场景 |
复杂SPA/微前端 |
轻量级应用/原型开发 |
配置复杂度 |
较高 |
较低 |
🏆 最佳实践建议
+ 中小项目使用Vite获得更快体验
+ 大型项目采用Webpack + Module Federation
+ 渐进式迁移老旧Webpack项目到Vite
+ 推荐工具链:Webpack 5 + Babel 7 + TypeScript 4
+ 必装插件:webpack-bundle-analyzer
- 避免:在生产环境使用eval-source-map