Webpack Bundle Analyzer

repository·main·Indexed 11 days ago

https://github.com/webpack/webpack-bundle-analyzer

A Webpack plugin and CLI utility (version 5.3.1) that visualizes the size of webpack output files using an interactive, zoomable treemap. It helps developers identify large modules and optimize bundle sizes by reporting stat, parsed, gzip, brotli, and zstd sizes.

Tokens
3.4K
Snippets
11
Records
18
Agent score
93%

What's inside Webpack Bundle Analyzer

  1. Understand size definitions

    main

    The analyzer reports several types of module sizes. You can control which is shown by default using defaultSizes:

    • stat: The "input" size of your files, before any transformations like minification. Obtained from Webpack's stats object.
    • parsed: The "output" size of your files (e.g., the minified size after using Uglify/Terser).
    • gzip: The size of the parsed bundles/modules after gzip compression.
    • brotli: The size of the parsed bundles/modules after Brotli compression.
    • zstd: The size of the parsed bundles/modules after Zstandard compression (requires Node.js 22.15.0+).
  2. Use webpack-bundle-analyzer as a Webpack plugin

    main

    To visualize your bundles during the webpack build process, import BundleAnalyzerPlugin and add it to your webpack.config.js plugins array.

    const { BundleAnalyzerPlugin } = require("webpack-bundle-analyzer");
    
    module.exports = {
      plugins: [new BundleAnalyzerPlugin()],
    };
  3. Filter chunks in the report

    main

    Once the report is open, you can filter the displayed chunks:

    • Sidebar: Click the > button at the top left. Under "Show chunks", select or deselect specific chunks.
    • Chunk Context Menu: Right-click (or Ctrl-click) a specific chunk to:
      • Hide chunk: Hides the selected chunk.
      • Hide all other chunks: Hides everything except the selected chunk.
      • Show all chunks: Resets the view to show all chunks.
  4. Use different analyzer modes

    main

    You can control how the analyzer outputs data using the analyzerMode option:

    • server (Default): Starts a local web server (e.g., at http://127.0.0.1:8888) to host the interactive visualization. This is ideal for development.
    • static: Generates a standalone HTML file in your Webpack output directory. This is useful for CI/CD pipelines or sharing reports.
    • json: Generates a JSON report file. Useful if you want to process the bundle data programmatically.
    • disabled: Prevents the analyzer from running. This can be useful to toggle the plugin via environment variables.
    // Example: Generate a static HTML report instead of a server
    new BundleAnalyzerPlugin({
      analyzerMode: 'static',
      reportFilename: 'report.html'
    })
  5. Generate a Webpack stats file

    main

    If you want to save the raw Webpack stats data (the JSON output from stats.toJson()) in addition to the visual report, set generateStatsFile to true and provide a statsFilename.

    The file will be saved to your Webpack output directory.

    new BundleAnalyzerPlugin({
      generateStatsFile: true,
      statsFilename: 'my-stats.json',
      // You can also pass custom Webpack stats options
      statsOptions: {
        assets: true,
        modules: true,
      }
    })
  6. Troubleshoot: Blank report in Jenkins

    main

    If your static HTML report appears blank in Jenkins, it is due to Jenkins' Content Security Policy (CSP) blocking the JavaScript required to render the report.

    To resolve this, you must relax the Jenkins CSP for Directory Browser Support by adjusting the hudson.model.DirectoryBrowserSupport.CSP setting.

  7. Troubleshoot: Limited output in stats.json

    main
    If your stats.json file contains insufficient information, check your Webpack configuration. If you have stats: 'error-only' set, the analyzer will not have enough data to work with. Remove that setting or use a more detailed stats configuration.
  8. Troubleshoot: Missing gzip or parsed sizes

    main

    If you only see stat sizes and not gzip or parsed sizes, it is likely because the files do not exist on your file system. This commonly happens when using webpack-dev-server, which keeps files in RAM.

    If running via CLI, you will see: Error parsing bundle asset "your_bundle_name.bundle.js": no such file.

    To fix this, ensure the files are actually written to disk before running the analyzer.

  9. Use absolute output paths for reports and stats

    main

    By default, reportFilename and statsFilename are relative to the webpack output.path. To write files outside of the bundle directory, provide absolute paths using path.resolve.

    const path = require("node:path");
    const { BundleAnalyzerPlugin } = require("webpack-bundle-analyzer");
    
    module.exports = {
      plugins: [
        new BundleAnalyzerPlugin({
          analyzerMode: "static",
          reportFilename: path.resolve(__dirname, "reports/report.html"),
          generateStatsFile: true,
          statsFilename: path.resolve(__dirname, "reports/stats.json"),
        }),
      ],
    };
  10. Configure BundleAnalyzerPlugin options

    main

    The BundleAnalyzerPlugin is the primary entry point for integrating the analyzer into your Webpack configuration. You can pass an Options object to its constructor to control how reports are generated and how the analyzer server behaves.

    Available Options

    OptionTypeDefaultDescription
    analyzerMode'static' | 'json' | 'server' | 'disabled''server'Determines how the report is delivered. 'server' starts a local server, 'static' generates an HTML file, 'json' generates a JSON file, and 'disabled' turns off the analyzer.
    analyzerHoststring'127.0.0.1'The host address for the analyzer server.
    analyzerPort'auto' | number8888The port for the analyzer server. Use 'auto' to let the system pick an available port.
    compressionAlgorithmstring'gzip'The algorithm used to calculate compressed sizes (e.g., 'gzip', 'brotli', 'zstd').
    reportFilenamestringnullThe name of the generated report file (e.g., 'report.html' or 'report.json').
    reportTitlestring | (() => string)utils.defaultTitleThe title displayed in the report.
    defaultSizes'stat' | 'parsed' | 'gzip' | 'brotli' | 'zstd''parsed'The default size metric to display in the report.
    openAnalyzerbooleantrueWhether to automatically open the browser when the analyzer starts.
    generateStatsFilebooleanfalseIf true, the plugin will also save a Webpack stats JSON file.
    statsFilenamestring'stats.json'The filename for the generated Webpack stats file.
    statsOptionsstring | boolean | StatsOptionsundefinedOptions passed to Webpack's stats.toJson() method.
    excludeAssetsstring | RegExp | ((asset: string) => void) | null | Pattern[]nullA pattern or array of patterns to exclude specific assets from the report.
    logLevel'info' | ...'info'The logging level for the plugin.
    analyzerUrlstring | (() => string)utils.defaultAnalyzerUrlThe URL used to start the analyzer.
    const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
    
    module.exports = {
      plugins: [
        new BundleAnalyzerPlugin({
          analyzerMode: 'static',
          reportFilename: 'bundle-report.html',
          openAnalyzer: true,
        }),
      ],
    };