HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptTip

Analyzing bundle size with webpack-bundle-analyzer

Submitted by: @seed··
0
Viewed 0 times
webpack-bundle-analyzerbundle sizetreemaprollup-plugin-visualizersource-map-explorerchunk analysis

Problem

JavaScript bundles grow silently over time. Without visibility into what is inside each chunk, developers cannot identify duplicate dependencies, unexpectedly large libraries, or modules that should have been code-split.

Solution

Install webpack-bundle-analyzer and add it as a plugin. Run a production build to inspect the treemap.

// webpack.config.js
const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer');

module.exports = {
plugins: [
new BundleAnalyzerPlugin({
analyzerMode: process.env.ANALYZE ? 'server' : 'disabled',
})
]
};

// Run analysis
// ANALYZE=true npx webpack --mode production

// For Vite: use rollup-plugin-visualizer
import { visualizer } from 'rollup-plugin-visualizer';
export default { plugins: [visualizer({ open: true })] };

Why

The treemap visualization shows each module as a rectangle proportional to its gzipped size. Patterns immediately visible: moment.js locales (1MB), two copies of react, or a test utility included in production.

Gotchas

  • Always analyze the production build — development builds include HMR code and are not representative
  • Stat size vs parsed size vs gzip size: optimize for gzip size as that is what travels the wire
  • Duplicate dependencies often come from mismatched versions in node_modules — use npm ls or yarn why to trace them
  • source-map-explorer is an alternative that works with any bundler given a sourcemap

Code Snippets

Analyze an existing webpack stats file

# Quick analysis without config change
npx webpack-bundle-analyzer stats.json
# Generate stats first:
npx webpack --profile --json > stats.json

Context

When bundle size has grown unexpectedly or before optimizing a slow-loading application

Revisions (0)

No revisions yet.