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

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

相关推荐
字节跳动数据库1 小时前
文章分享——相似函数处理方法
人工智能·后端·程序员
Bigfish_coding1 小时前
前端转agent-【python】-12 LangChain 入门实战:RAG + LCEL 链式调用
人工智能
程序员cxuan2 小时前
读懂 Claude Code 架构分析系列,第一篇,开始!
人工智能·后端·架构
饼干哥哥2 小时前
扣子3.0测评:我让 Codex 和 Claude Code 住同一个桌面,结果它们打架了!
人工智能·开源·代码规范
Token炼金师3 小时前
IP-Adapter:解耦交叉注意力如何让扩散模型看见图像
人工智能
Bigfish_coding3 小时前
前端转agent-【python】-11 LangGraph 高级特性:时间旅行与人工介入
人工智能
Token炼金师3 小时前
从safetensors到像素:ComfyUI Checkpoint加载机制的底层拆解
人工智能
AI闲人3 小时前
AI 写代码越来越快,为什么 Code Review 反而更慢了?
人工智能·code review·ai 编程
武子康3 小时前
调查研究-202 SGLang 深度解析:为什么大模型推理框架不只是“把模型跑起来“
人工智能·openai·agent
我是大卫3 小时前
Trae 读取 agents.md 并驱动 AI 完整底层原理
人工智能