Bundle size: why tree shaking fails
React chapter 146 · Web Perf · ch.7 · tree shaking, ESM vs CommonJS, namespaces, duplicate libraries · source: bundle size, tree shaking, non-tree-shakable libraries, transitive dependencies
The problem
The app uses one icon, one MUI component, two lodash helpers and formats one date — yet the vendor chunk is megabytes. A namespace object (Ui = { Icons }), a CommonJS library and three date libraries each defeat tree shaking in a different way.
The pattern that fixes it
Open the bundle analyzer, click the biggest block, find the import that pulled it in. Import exactly what you use from ES-module entry points, drop non-tree-shakable libraries or use their per-function paths, keep one library per job, and lazy-load heavy page-only code.
In plain words
Your bundler copies only the code you actually use into the files users download — “tree shaking”. But it can only prove what is unused when imports are simple and static. A few common habits make it give up and include the whole library.
Packing for a trip by reading your itinerary. If the itinerary says “I might need anything from the garage”, the whole garage goes in the suitcase.
Terms
- tree shaking
- Removing exports nothing imports. Works on static import/export (ES modules).
- ESM vs CommonJS
- export const x is analysable at build time. module.exports = {…} is just an object at runtime — usually included whole. Check with npx is-esm <pkg>.
- bundle analyzer
- A treemap of what is in each chunk: rollup-plugin-visualizer (Vite), webpack-bundle-analyzer, @next/bundle-analyzer.
Going deeper
Bytes cost twice
A big bundle costs download time (bad on slow networks, chapter 143) and then parse + compile + evaluate time on the main thread (bad on slow CPUs, it delays LCP in CSR and blocks hydration in SSR). Gzip/Brotli shrink the download, not the parse: the phone still evaluates every minified byte.
Why the namespace object breaks it
import * as Icons alone is fine — the bundler sees Icons.Star and keeps only Star. But export const Ui = { Icons } turns the namespace into a runtime value that could be read with any key (Ui.Icons[name]). The bundler must keep every export. The same happens with re-export barrels that have side effects, or "sideEffects" missing from a library’s package.json.
Transitive dependencies and duplicates
A package you never imported can be in the bundle because a dependency of a dependency needs it — sometimes in a second version. npm why <pkg> shows the chain. Duplicates (moment + luxon + date-fns, two copies of a library at different versions) are common in big multi-team apps; dedupe with one library per job and package-manager overrides/resolutions.
Guard it in CI
Bundle size regressions arrive one innocent import at a time. Add a size budget (size-limit, bundlewatch, or the framework’s build output) to CI so the PR that adds 400 KB fails with a clear diff.
Keep learning
- Previous: INP: the three parts of a click
- Next: Put the LCP element on the critical path
- Related: lazy + preload
- Related: Request waterfalls
- Related: Yield to main
- Related: CSR blank vs SSR
- Related: React Compiler
- Related: Where LCP time goes
Overview
react + react-dom your app code A namespace re-exported as an object value: every one of ~2,000 icons is kept. one icon, own entry point Same pattern: keeps the whole kit. named import, ESM tiptap + prosemirror Rich-text editor imported statically, but only the Inbox page uses it. moved to an Inbox-only chunk moment + luxon + date-fns Three teams, three date libraries, each used once. moment is CommonJS and not tree-shakable. one library, tree-shaken loads the CommonJS build: all 300 helpers for . Real life: a dashboard that uses a handful of components ships a ~4 MB bundle. Click the blocks. Inspect a library Same features. A fraction of the JavaScript. Untick fixes to see which line costs what. No new architecture: five import lines and one lazy(). Sizes are illustrative, (5 MB → under 700 KB). Untick only @mui/icons-material. One line is half the bundle. Untick lodash: 72 KB for two string helpers the language already has. Break everything then fix the biggest block first — same method as chapter 143.
More courses
- Jobs, linked to lessons — Browse jobs where every requirement links to the chapter that teaches it. See how ready you are, how long the gap takes to close, and which listings look stale.
- Match a job post to courses — Paste a job post. Each skill is matched to a track here and put in learning order, foundations first.
- Databases in depth — How a query becomes work. Indexes, isolation, locks, and the plans that explain why a page is slow — not an ORM tour.
- System Design — Core concepts first (SQL vs NoSQL, CAP, indexing, replication, sharding), then designs grouped by what carries them: the database, Redis, Kafka, or many services.
- NestJS: build a real API — One ticket-booking API, built in order: a plain Node server first, then NestJS modules, validation, a real database, and the features real clients lean on.
- Microservices — Microservice patterns one diagram at a time: how to split a monolith, how services talk, and how data stays consistent without distributed transactions.
- Kafka — A beginner-to-senior path through event logs, reliable delivery, production operations, and disaster recovery.
- AI engineering for software engineers — Eight free reads, in order, for software engineers moving into AI: when to build an agent, how to build one, how to test it, and how the model works underneath.
- Frontend system design — How a UI is sliced when it is a product, not a page: ownership of state, cache, routes, and what happens when the network lies.
- TypeScript in depth — The type system as a design tool. Inference, narrowing, generics, and the errors that mean the model is wrong — not a catalog of utility types.
- CSS in depth — See the box, then the page. Visual chapters from the box model through Flexbox surprises, Grid, selectors, and units, then backgrounds, shapes, and visual effects, each with a playground.
- Accessibility — Foundations first (WCAG in plain words, semantic HTML, lists, alt text), then hands-on HTML labs, a full pass of WAI-ARIA 1.3, and a final fix-the-page challenge.
- Docker — What an image is, why layers cache, and how containers find each other on a network.
- Redis — Fifteen Redis patterns, one picture each: cache, session, lock, counter, rate limiter, queue, and when Redis is the wrong tool.
- Kubernetes — Kubernetes from zero to operators: why it exists, Pods, Deployments and Services, then configuration, networking, storage, scheduling, scaling and security.
- AWS — AWS networking in plain English. A VPC is a gated housing society: streets are subnets, the Internet Gateway is the main gate, and a route table is the signboard.
- Networking: the NetRoute game — NetRoute is a packet logistics game. You wire up computers, switches, routers, firewalls and gateways, set each device, and watch glowing packets travel. If a packet gets dropped, the game shows you which header field was wrong.