Tree Shaking vs Code Splitting Explained
On this page
Learning Objective
Explain how bundlers remove unused code through static analysis, write and choose packages that tree shake well, understand the role of side effects, and split code by route and by feature with dynamic imports so users download only what the current screen needs.
Concept Explanation
Every byte of JavaScript costs users twice: once to download and again to parse, compile and execute on the main thread. Two techniques keep that cost down. Tree shaking removes code that is never used. Code splitting divides the code that is used into chunks that load only when needed. Both rely on the static structure of ES modules from Day 38.
Tree shaking works by marking exports that are actually imported and following them through the graph; whatever is never reached is dropped from the output. It only works when the bundler can prove that removing code is safe. Static named imports and exports make that analysis possible, which is why ES modules tree shake and CommonJS mostly does not. Importing a single function from a library written as ES modules with many small exports can include just that function, while importing from a CommonJS build pulls in the whole library.
Side effects are the main obstacle. A module has side effects if merely importing it does something: modifying globals, registering a polyfill, injecting CSS. A bundler cannot drop a module with side effects even if none of its exports are used, so it must assume side effects unless told otherwise. Packages declare "sideEffects": false in package.json to promise that their modules are pure, or list the files that do have effects, such as CSS. Patterns that defeat tree shaking include exporting one large object of utilities, classes with many methods where only one is needed, barrel files that re-export an entire library, and top-level code that runs on import.
Code splitting decides what loads when. The most effective split is by route: each page of the application is a dynamic import, so the home page does not download the checkout or the admin dashboard. Most routers and meta-frameworks do this automatically. The second is by feature: heavy components such as a rich text editor, a map, a chart library or a video player load when the user opens them. Shared code that several chunks need is extracted into common chunks, so it is downloaded once and cached.
Splitting has trade-offs. Too many tiny chunks create request overhead and waterfalls, where one chunk's download reveals the need for another. Loading a chunk on click adds latency to that interaction, so prefetch likely next routes during idle time or on hover, and show a fallback while a chunk loads. The goal is not the smallest possible initial bundle at any cost; it is to ensure that the code needed for the first view arrives quickly and that everything else arrives before the user needs it.
| Technique | How | Benefit |
|---|---|---|
| Tree shaking | Static ES module imports and exports | Unused exports removed |
| sideEffects flag | "sideEffects": false in package.json | Unused modules dropped entirely |
| Direct imports | import debounce from 'lodash-es/debounce' | Avoids pulling a whole library |
| Route splitting | lazy(() => import('./pages/Checkout')) | Pages load when visited |
| Feature splitting | Load the editor on open | Heavy widgets stay out of first load |
| Shared chunks | Bundler extracts common modules | Downloaded once, cached |
| Prefetching | On hover or idle | Hides the cost of a split |
Worked Example: Splitting Routes and a Heavy Editor in React
Routes are lazy loaded with a shared fallback, the markdown editor loads only when the user starts writing, and the next likely route is prefetched on hover.
import { lazy, Suspense, useState } from 'react';
import { createBrowserRouter, RouterProvider, Link } from 'react-router';
// Route-level splitting: each page becomes its own chunk
const Home = lazy(() => import('./pages/Home'));
const Product = lazy(() => import('./pages/Product'));
const Checkout = lazy(() => import('./pages/Checkout'));
const router = createBrowserRouter([
{ path: '/', element: <Home /> },
{ path: '/p/:id', element: <Product /> },
{ path: '/checkout', element: <Checkout /> },
]);
export function App() {
return (
<Suspense fallback={<PageSkeleton />}>
<RouterProvider router={router} />
</Suspense>
);
}
// Prefetch the checkout chunk when the user shows intent
const prefetchCheckout = () => import('./pages/Checkout');
export function CartButton() {
return <Link to="/checkout" onMouseEnter={prefetchCheckout} onFocus={prefetchCheckout}>Checkout</Link>;
}
// Feature splitting: the editor and its dependencies load on demand
const MarkdownEditor = lazy(() => import('./components/MarkdownEditor'));
export function ReviewForm() {
const [writing, setWriting] = useState(false);
return writing ? (
<Suspense fallback={<p>Loading editor...</p>}><MarkdownEditor /></Suspense>
) : (
<button onClick={() => setWriting(true)}>Write a review</button>
);
}// Tree shaking friendly versus unfriendly imports
import { debounce } from 'lodash-es'; // ES module build: only debounce is bundled
// import _ from 'lodash'; // CommonJS build: the whole library is bundledRunning the build with a bundle analyzer such as rollup-plugin-visualizer shows the Checkout page and the editor as separate chunks, and confirms that only debounce from lodash-es made it into the main bundle.
Real-World Examples
- The HTTP Archive Web Almanac reports that the median mobile page ships several hundred kilobytes of JavaScript and that a large share of downloaded JavaScript is unused during page load, which Chrome's Coverage panel and Lighthouse's "Reduce unused JavaScript" audit measure directly.
- Lodash publishes lodash-es, an ES module build, alongside its CommonJS build so that bundlers can tree shake individual functions, and date libraries such as date-fns were designed as collections of small, separately importable functions for the same reason.
Review Questions & Answers
require calls and module.exports assignments are ordinary run-time code that can be dynamic, so the bundler cannot reliably determine which exports are used without executing the code. ES module imports and exports are static declarations that can be analyzed safely.
That importing the package's modules has no effects beyond defining exports. If none of a module's exports are used, the bundler may drop the module entirely. Packages with CSS imports or polyfills should list those files instead of declaring false.
Splitting by route, so each page is loaded only when the user navigates to it. Routes are natural, independent boundaries, and most routers and frameworks support lazy routes directly.
Many tiny chunks add request and module overhead, and chains of dynamic imports create waterfalls where loading one chunk reveals the need for the next. Interactions that wait for a chunk also feel slower, so splits should follow real usage and be paired with prefetching.