webpack-bundle-analyzer Guide
webpack-bundle-analyzer generates an interactive treemap of your JavaScript bundle, showing exactly what's inside each chunk. Use it to find bloated dependencies, duplicate packages, and dead code costing your users download time.
Installation & Basic Setup
npm install --save-dev webpack-bundle-analyzer
// webpack.config.js
const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer');
module.exports = {
// ... other config
plugins: [
// Opens browser with interactive treemap
new BundleAnalyzerPlugin({
analyzerMode: 'server', // 'server' | 'static' | 'json' | 'disabled'
analyzerPort: 8888,
openAnalyzer: true,
generateStatsFile: true, // also write stats.json
statsFilename: 'stats.json',
}),
],
}; npm Script Integration
// package.json — only run analyzer when needed
{
"scripts": {
"build": "webpack --mode production",
"build:analyze": "ANALYZE=true webpack --mode production",
"analyze": "webpack-bundle-analyzer dist/stats.json"
}
}
// webpack.config.js — conditional plugin
const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer');
const plugins = [];
if (process.env.ANALYZE) {
plugins.push(new BundleAnalyzerPlugin());
} Size Metrics Explained
| Size Type | What It Measures | Optimize For? |
|---|---|---|
| Stat size | Raw input file size before webpack processing | No |
| Parsed size | After minification and dead code elimination | Secondary |
| Gzip size | Compressed size — what users actually download | Primary |
Common Bundle Bloat & Fixes
| Bloat Source | Before | Fix | After |
|---|---|---|---|
| moment.js | 66KB gzip | Switch to day.js | 2KB gzip |
| Full lodash | 24KB gzip | lodash-es + tree shake | 1–3KB gzip |
| All locales | 50KB+ gzip | ContextReplacementPlugin | 2KB gzip |
| Unsplit routes | 500KB+ main | Dynamic import() | 50KB main |
Code Splitting with Dynamic Imports
// Before: static import bundles everything together
import AdminDashboard from './AdminDashboard';
// After: dynamic import creates separate chunk
const AdminDashboard = React.lazy(() => import('./AdminDashboard'));
// Route-level splitting with React Router
const routes = [
{
path: '/dashboard',
component: React.lazy(() => import('./pages/Dashboard')),
},
{
path: '/admin',
component: React.lazy(
() => import(/* webpackChunkName: "admin" */ './pages/Admin')
),
},
];
// webpack.config.js: vendor chunk splitting
optimization: {
splitChunks: {
chunks: 'all',
cacheGroups: {
vendor: {
test: /[\\/]node_modules[\\/]/,
name: 'vendors',
priority: 10,
},
react: {
test: /[\\/]node_modules[\\/](react|react-dom)[\\/]/,
name: 'react',
priority: 20,
},
},
},
} Frequently Asked Questions
How do I install and run webpack-bundle-analyzer?▼
Install as a dev dependency: `npm install --save-dev webpack-bundle-analyzer`. Then add it to your webpack config plugins array: `new BundleAnalyzerPlugin()`. Run your build with `npm run build` and the analyzer opens a browser with a treemap visualization. For a JSON report without opening a browser, set `analyzerMode: 'json'` and `reportFilename: 'stats.json'`.
What is the difference between stat size, parsed size, and gzip size?▼
Stat size is the raw file size before any webpack transformations (minification, tree-shaking). Parsed size is the size after webpack processes the file (minified, dead code removed). Gzip size is the parsed size after gzip compression — this is what users actually download. Always optimize for gzip size since that's the real network cost. Brotli typically gives 10–15% better compression than gzip for text assets.
What should I look for in the bundle analyzer treemap?▼
Look for: (1) Large node_modules taking disproportionate space — candidates for code-splitting or replacement with lighter alternatives. (2) Duplicate packages — multiple versions of lodash, React, etc. (3) Dev-only code included in production (test utilities, mock data). (4) Full libraries when only a few functions are used (e.g., importing all of lodash instead of lodash/pick). (5) Locale/i18n files for all languages when only one is needed (moment.js locale bloat).
How do I reduce my webpack bundle size?▼
Key techniques: (1) Code splitting — use dynamic `import()` for routes/features. (2) Tree shaking — use ES modules and set `sideEffects: false` in package.json. (3) Replace heavy libraries — swap moment.js for day.js (66KB vs 2KB), lodash for lodash-es with tree shaking. (4) Lazy-load non-critical components. (5) Configure `optimization.splitChunks` to extract vendor chunks. (6) Use `webpackPrefetch: true` for routes likely to be visited.
Related Products
on GumroadTypeScript Quick Reference Toolkit
5 practical reference files for TypeScript developers: cheatsheet, TS vs JS comparison, 20 utility types with real examples, tsconfig best practices template, and 15 common mistakes guide. Print it. Keep it on your desk.
Buy on Gumroad →Developer Productivity Bundle
Stop rebuilding the same setup every project. 51 VSCode snippets, 40 Git aliases, 5 Docker Compose stacks, 5 GitHub Actions workflows, 5 README templates, and a dotfiles kit. Set up a professional dev environment in under an hour.
Buy on Gumroad →AI Prompt Engineering Toolkit
58 structured prompt templates for Claude, ChatGPT, and Gemini — organized by use case. Code Review, Debugging, Documentation, Architecture, and 10 model-specific tips. Stop writing prompts from scratch.
Buy on Gumroad →You Might Also Need
Web Performance Checklist
Interactive web performance checklist covering images, fonts, JavaScript, CSS, caching, and server. Check off items to track your score out of 100 and export as Markdown.
Open free tool →
JS Prototype Chain Visualizer
Explore JavaScript prototype chains interactively. Visualize built-in types (Array, Map, Promise, Error) and custom classes with property lookup path diagrams.
Open free tool →
Code Tools
10 free code tools: HTML/CSS/JS formatter and minifier, SQL formatter, TypeScript to JavaScript converter, JSON formatter, regex playground, and Git helpers. No signup.
Open free tool →
More Free Tools
Related Articles
Vite 6 vs Webpack 5 深度對決:2026 大型專案遷移實戰指南
2026 年最完整的 Vite 6 vs Webpack 5 深度比較與遷移指南。涵蓋效能基準測試、分塊策略、CSS Modules、環境變數轉換、常見陷阱與真實大型專案遷移清單。
Performance Optimization 2026: Complete Guide to Frontend, Backend, and Infrastructure
Comprehensive performance optimization guide for 2026 covering Core Web Vitals, JavaScript bundle optimization, server-side rendering, caching strategies, database query optimization, CDN configuration, and real-world benchmarks.
esbuild: The Fastest JavaScript Bundler - Complete Guide 2026
A complete guide to esbuild: configuration, plugins, benchmarks vs webpack and Vite, migration guide, and real-world usage patterns. Why esbuild is the fastest JavaScript bundler.
Rspack vs Webpack 5: Rust-Powered Bundling Speed in 2026
Deep dive into Rspack vs Webpack 5 in 2026. Performance benchmarks (5-10x faster), webpack plugin compatibility, migration guide, and when to switch to the Rust-powered bundler from ByteDance.
Vite 6 vs webpack vs esbuild vs Turbopack: Build Tool Comparison 2026
In-depth 2026 comparison of JavaScript build tools: Vite 6, webpack 5, esbuild, and Turbopack. Build speeds, HMR, plugin ecosystems, migration paths, and when to use each.
Enjoying this tool? Get more like it.
Weekly developer tool guides, productivity playbooks & AI tricks. Free. No spam.
Unlock AI-Powered Dev Tools
- ⚡ AI Code Review, Doc Generator & SQL Builder
- ⚡ All premium templates & early access
- ⚡ Member discounts on Gumroad products
$9/mo after trial · Cancel anytime
Want the full toolkit?
Get DevPlaybook Pro
Every template, guide, boilerplate, and automation script in one bundle. 13 premium products — grab them all at once and save big.
MIT licensed · Instant download · No subscription
See what's included → Browse all deals →