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 小时前
谷歌:“课程学习”融入扩散模型强化学习
人工智能·语言模型·自然语言处理·论文笔记
AIGCmagic社区1 小时前
具身智能专题:机器人也有Scaling Law?智元GE-Act 2.0用3万小时真机数据给出答案
人工智能·aigc·具身智能
Rosanci2 小时前
谷歌浏览器插件开发实战指南:从 Hello World 到上架发布
大数据·人工智能·chrome·程序人生
明月_清风2 小时前
AI 越来越强,程序员真正的价值到底是什么?
人工智能·后端
m0_466525293 小时前
云从科技上线云起ModelHub:AI团队时代的模型算力基础设施
大数据·人工智能·科技
火山引擎开发者社区3 小时前
OpenViking:给 Codex 加上长期记忆
人工智能
荆棘鸟智能3 小时前
城市感知设备怎么统一接入?从多协议网关到设备模型的中间件架构设计
人工智能·算法·边缘计算
火山引擎开发者社区3 小时前
当 AI 内容真假难辨,谁来为真实签名 —— 证书中心 C2PA 内容可信溯源服务正式发布
人工智能
百万蹄蹄向前冲3 小时前
风扇转了一晚上MVP专家团翻车事故
前端·人工智能
米小虾3 小时前
你的 harness 技巧有保质期:176 组对照实验显示,上下文管理的收益从 35.7 分跌到 2.7 分
人工智能·agent