All topics
Performanceintermediate

Bundle Size Analysis and Tree Shaking

Learn how to analyze what's contributing to a React app's bundle size and how tree shaking eliminates unused code.

Bundle size directly affects how much JavaScript a user's browser must download, parse, and execute before an app becomes interactive, so understanding what's contributing to that size is a practical performance skill. Tools like webpack-bundle-analyzer or Vite's rollup-plugin-visualizer render a treemap of exactly which modules and dependencies make up the final bundle and how large each one is, making it easy to spot an unexpectedly large library or a duplicate dependency.

A bundle analyzer is like an itemized moving-truck manifest showing exactly which boxes take up the most space, so you can spot the surprisingly huge box (an oversized dependency) worth reconsidering; tree shaking is like a packer who only puts in the specific items from each box you've actually said you'll use, leaving the rest of that box's contents behind entirely.

Key Concepts

1
Tree shaking is the process, performed by modern bundlers (webpack, Rollup, esbuild, Vite), of statically analyzing ES module import/export statements to determine which exported values are actually used, and eliminating (shaking out) unused exports from the final bundle. This only works reliably with genuine ES modules (import/export), not CommonJS (require/module.exports), since ES module imports are statically analyzable at build time while CommonJS requires are dynamic and much harder to safely eliminate.
importexportrequiremodule.exports
2
A common bundle-size pitfall is importing an entire utility library's default export (import _ from 'lodash') when only one function is actually used, pulling in the whole library instead of just that function; using named imports from an ES-module-friendly build (import debounce from 'lodash-es/debounce' or named imports from lodash-es) allows tree shaking to eliminate the rest.
import _ from 'lodash'import debounce from 'lodash-es/debounce'lodash-es
3
Interviewers ask about bundle analysis and tree shaking to see if a candidate has practical experience diagnosing a bloated production bundle rather than only theoretical awareness — a good answer describes actually running a bundle analyzer, identifying a specific oversized dependency, and either replacing it, importing it more surgically, or code-splitting it to a route/feature that doesn't need it in the main bundle.