阿里云主机折上折
  • 微信号
Current Site:Index > Bundle size analysis and optimization

Bundle size analysis and optimization

Author:Chuan Chen 阅读数:13685人阅读 分类: 性能优化

Bundle Size Analysis Tool

Webpack Bundle Analyzer is currently the most commonly used bundle size visualization tool. It generates an interactive treemap that intuitively displays the proportion of each module in the final bundle. Installation method:

npm install --save-dev webpack-bundle-analyzer

Configuration example:

const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;

module.exports = {
  plugins: [
    new BundleAnalyzerPlugin({
      analyzerMode: 'server',
      generateStatsFile: true,
      statsOptions: { source: false }
    })
  ]
}

After running the build, a local server will launch to display the analysis results. The visualization clearly shows:

  • The actual size of each module
  • Dependency relationships between modules
  • Cases of duplicate dependencies
  • The proportion of third-party libraries

Code Splitting Strategies

Dynamic imports are the core method for achieving code splitting. Webpack automatically splits when it encounters the import() syntax:

// Static import
import { heavyModule } from './heavyModule';

// Dynamic import
const loadHeavyModule = () => import('./heavyModule');

Common route-level code splitting in React projects:

import React, { Suspense, lazy } from 'react';
const Home = lazy(() => import('./routes/Home'));
const About = lazy(() => import('./routes/About'));

function App() {
  return (
    <Suspense fallback={<div>Loading...</div>}>
      <Router>
        <Route path="/" exact component={Home} />
        <Route path="/about" component={About} />
      </Router>
    </Suspense>
  );
}

Dependency Optimization Techniques

Third-party libraries are often the main cause of bundle bloat. Optimization solutions for different scenarios:

  1. On-demand loading for component libraries
// Wrong - full import
import { Button, Select } from 'antd';

// Correct - on-demand import
import Button from 'antd/lib/button';
import Select from 'antd/lib/select';
  1. Replace bloated libraries
  • Use date-fns instead of moment.js
  • Use lodash-es instead of the full lodash
  • Use preact compatibility layer instead of react
  1. Use CDN links
<script src="https://cdn.jsdelivr.net/npm/react@17/umd/react.production.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/react-dom@17/umd/react-dom.production.min.js"></script>

Build Configuration Optimization

Webpack production environment configuration example:

module.exports = {
  optimization: {
    splitChunks: {
      chunks: 'all',
      cacheGroups: {
        vendors: {
          test: /[\\/]node_modules[\\/]/,
          priority: -10
        },
        default: {
          minChunks: 2,
          priority: -20,
          reuseExistingChunk: true
        }
      }
    },
    minimizer: [
      new TerserPlugin({
        parallel: true,
        extractComments: false,
      }),
      new CssMinimizerPlugin(),
    ]
  },
  performance: {
    maxEntrypointSize: 512000,
    maxAssetSize: 512000
  }
}

Key configuration items explained:

  • splitChunks: Automatically splits node_modules and common modules
  • treeShaking: Removes unused exported code
  • scopeHoisting: Hoists module scope to reduce closures
  • minimize: Enables code compression

Advanced Compression Techniques

  1. Image resource optimization
module: {
  rules: [
    {
      test: /\.(png|jpe?g|gif)$/i,
      use: [
        {
          loader: 'image-webpack-loader',
          options: {
            mozjpeg: { progressive: true, quality: 65 },
            optipng: { enabled: false },
            pngquant: { quality: [0.65, 0.90], speed: 4 },
            gifsicle: { interlaced: false },
          }
        }
      ]
    }
  ]
}
  1. Gzip/Brotli compression
# Install compression plugin
npm install compression-webpack-plugin --save-dev

# Webpack configuration
const CompressionPlugin = require("compression-webpack-plugin");
plugins: [
  new CompressionPlugin({
    algorithm: 'brotliCompress',
    filename: '[path][base].br',
    test: /\.(js|css|html|svg)$/,
    threshold: 10240,
    minRatio: 0.8,
  })
]

Continuous Monitoring Solutions

Integration into CI/CD pipeline for size monitoring:

  1. Use webpack-stats-plugin to generate build reports
const { StatsWriterPlugin } = require("webpack-stats-plugin");

plugins: [
  new StatsWriterPlugin({
    filename: "stats.json",
    fields: ["assets", "modules"]
  })
]
  1. Configure size threshold warnings
performance: {
  hints: 'warning',
  maxEntrypointSize: 500000, // 500kb
  maxAssetSize: 300000 // 300kb
}
  1. Integrate BundleWatch for automated monitoring
# .bundlewatch.config.json
{
  "files": [
    {
      "path": "dist/*.js",
      "maxSize": "100kB"
    }
  ]
}

本站部分内容来自互联网,一切版权均归源网站或源作者所有。

如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn

Front End Chuan

Front End Chuan, Chen Chuan's Code Teahouse 🍵, specializing in exorcising all kinds of stubborn bugs 💻. Daily serving baldness-warning-level development insights 🛠️, with a bonus of one-liners that'll make you laugh for ten years 🐟. Occasionally drops pixel-perfect romance brewed in a coffee cup ☕.