Webpack优化实战:从配置到性能调优
大家好,我是蔓蔓。在大厂工作时,我负责过多个大型项目的Webpack配置和优化。今天我来和大家分享Webpack优化的实战技巧。
基础优化
合理配置mode
// webpack.config.js module.exports = { mode: process.env.NODE_ENV === 'production' ? 'production' : 'development' };优化resolve配置
const path = require('path'); module.exports = { resolve: { // 配置路径别名 alias: { '@': path.resolve(__dirname, 'src'), '@components': path.resolve(__dirname, 'src/components'), '@utils': path.resolve(__dirname, 'src/utils') }, // 减少文件查找范围 extensions: ['.js', '.jsx', '.ts', '.tsx', '.json'], // 配置模块查找路径 modules: [path.resolve(__dirname, 'node_modules')] } };代码分割
入口分割
module.exports = { entry: { main: './src/main.js', vendor: ['react', 'react-dom', 'lodash'] }, optimization: { splitChunks: { chunks: 'all', cacheGroups: { vendor: { test: /[\\/]node_modules[\\/]/, name: 'vendors', chunks: 'all' }, common: { name: 'common', minChunks: 2, chunks: 'all', priority: -10, reuseExistingChunk: true } } } } };动态导入
// 按需加载组件 const Home = () => import(/* webpackChunkName: "home" */ './pages/Home'); const About = () => import(/* webpackChunkName: "about" */ './pages/About'); // 路由懒加载 const routes = [ { path: '/', component: Home }, { path: '/about', component: About } ];压缩优化
代码压缩
const TerserPlugin = require('terser-webpack-plugin'); const CssMinimizerPlugin = require('css-minimizer-webpack-plugin'); module.exports = { optimization: { minimizer: [ new TerserPlugin({ terserOptions: { compress: { drop_console: true, drop_debugger: true } } }), new CssMinimizerPlugin() ] } };资源压缩
const CompressionPlugin = require('compression-webpack-plugin'); module.exports = { plugins: [ new CompressionPlugin({ algorithm: 'gzip', threshold: 8192, // 超过8KB的文件才压缩 minRatio: 0.8 // 压缩率低于80%才压缩 }) ] };缓存策略
文件名哈希
module.exports = { output: { filename: '[name].[contenthash].js', chunkFilename: '[name].[contenthash].chunk.js' } };模块缓存
const HardSourceWebpackPlugin = require('hard-source-webpack-plugin'); module.exports = { plugins: [ new HardSourceWebpackPlugin() ] };性能监控
速度分析
const SpeedMeasurePlugin = require('speed-measure-webpack-plugin'); const smp = new SpeedMeasurePlugin(); module.exports = smp.wrap({ // webpack配置 });体积分析
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin; module.exports = { plugins: [ new BundleAnalyzerPlugin() ] };进阶优化
Tree Shaking
module.exports = { optimization: { usedExports: true } }; // package.json { "sideEffects": false }Scope Hoisting
module.exports = { optimization: { concatenateModules: true } };懒加载图片
// 使用IntersectionObserver const lazyImages = document.querySelectorAll('img[data-src]'); const imageObserver = new IntersectionObserver((entries) => { entries.forEach(entry => { if (entry.isIntersecting) { const img = entry.target; img.src = img.dataset.src; imageObserver.unobserve(img); } }); }); lazyImages.forEach(img => imageObserver.observe(img));总结
Webpack优化是一个持续的过程,需要结合项目实际情况进行:
- 合理配置代码分割和懒加载
- 使用压缩和缓存策略
- 监控构建速度和包体积
- 利用Tree Shaking和Scope Hoisting
技术应当有温度,优化后的构建能提升开发和用户体验。