Webpack优化实战:从配置到性能调优

Webpack优化实战:从配置到性能调优

大家好,我是蔓蔓。在大厂工作时,我负责过多个大型项目的Webpack配置和优化。今天我来和大家分享Webpack优化的实战技巧。

基础优化

合理配置mode

javascript 复制代码
// webpack.config.js
module.exports = {
  mode: process.env.NODE_ENV === 'production' ? 'production' : 'development'
};

优化resolve配置

javascript 复制代码
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')]
  }
};

代码分割

入口分割

javascript 复制代码
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
        }
      }
    }
  }
};

动态导入

javascript 复制代码
// 按需加载组件
const Home = () => import(/* webpackChunkName: "home" */ './pages/Home');
const About = () => import(/* webpackChunkName: "about" */ './pages/About');

// 路由懒加载
const routes = [
  {
    path: '/',
    component: Home
  },
  {
    path: '/about',
    component: About
  }
];

压缩优化

代码压缩

javascript 复制代码
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()
    ]
  }
};

资源压缩

javascript 复制代码
const CompressionPlugin = require('compression-webpack-plugin');

module.exports = {
  plugins: [
    new CompressionPlugin({
      algorithm: 'gzip',
      threshold: 8192, // 超过8KB的文件才压缩
      minRatio: 0.8 // 压缩率低于80%才压缩
    })
  ]
};

缓存策略

文件名哈希

javascript 复制代码
module.exports = {
  output: {
    filename: '[name].[contenthash].js',
    chunkFilename: '[name].[contenthash].chunk.js'
  }
};

模块缓存

javascript 复制代码
const HardSourceWebpackPlugin = require('hard-source-webpack-plugin');

module.exports = {
  plugins: [
    new HardSourceWebpackPlugin()
  ]
};

性能监控

速度分析

javascript 复制代码
const SpeedMeasurePlugin = require('speed-measure-webpack-plugin');
const smp = new SpeedMeasurePlugin();

module.exports = smp.wrap({
  // webpack配置
});

体积分析

javascript 复制代码
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;

module.exports = {
  plugins: [
    new BundleAnalyzerPlugin()
  ]
};

进阶优化

Tree Shaking

javascript 复制代码
module.exports = {
  optimization: {
    usedExports: true
  }
};

// package.json
{
  "sideEffects": false
}

Scope Hoisting

javascript 复制代码
module.exports = {
  optimization: {
    concatenateModules: true
  }
};

懒加载图片

javascript 复制代码
// 使用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优化是一个持续的过程,需要结合项目实际情况进行:

  1. 合理配置代码分割和懒加载
  2. 使用压缩和缓存策略
  3. 监控构建速度和包体积
  4. 利用Tree Shaking和Scope Hoisting

技术应当有温度,优化后的构建能提升开发和用户体验。

相关推荐
豆包MarsCode3 分钟前
✍️ TRAE 双端融合,全面升级|征文活动开启,赢京东卡、TRAE 精美周边好礼!
人工智能
weixin_448119944 分钟前
Datawhale计算机中的数学#MCS #Mathematics #Maths #Yibo #翊博 #翊博在这里 #菲尔兹奖 #yibohere
人工智能
虹科网络安全7 分钟前
“顶会”看安全(十九):医疗 AI 中的差异化隐私风险
人工智能·经验分享·安全
人工智能AI技术8 分钟前
AI时代新Word来了,md和HTML本地文件人机协同编辑
人工智能
YH行业报告分析11 分钟前
2026费用管理软件工具市场洞察:AI Agent与RaaS模式如何重构企业费控流程?
人工智能·重构
szxinmai主板定制专家12 分钟前
电力边缘 AI 落地难点剖析:RK 系列 + FPGA 异构平台在储能监控终端的 EMC 与算力优化
人工智能·fpga开发·arm+fpga·rk3588+fpga
触底反弹13 分钟前
🎯 LangSmith 学习与面试全攻略:从 Agent「盲盒」到全链路观测与量化评估
人工智能·面试
用户83145509803129 分钟前
如一 Agent 架构解读(四):异步整理——压缩不该堵住用户
人工智能·llm
用户19172912708335 分钟前
团队 Agent 技能库怎么管?用 Git 做 Skill 版本化与复用实战
人工智能
Dawson Zhu35 分钟前
《Agentic Design Patterns》第 13 章导读:人机协同(Human-in-the-Loop)
人工智能·语言模型·架构·aigc·agi