ReactEasy
What is tree shaking?
Tree shaking is dead-code elimination for JavaScript modules: the bundler analyzes static import and export statements and drops exports that are never used from the final bundle. It works with ES modules and is done automatically in production builds by Vite (Rolldown), webpack, Turbopack and esbuild.
Requirements
- ES modules (
import/export): they are static, so the bundler knows at build time what is used. CommonJS (require) is dynamic and largely not shakable. - No side effects on import: if importing a module runs code (polyfills, global CSS, registering plugins), the bundler must keep it. Packages declare
"sideEffects": false(or a list of files) inpackage.jsonto allow removal. - Production mode: minifiers remove the unused code.
Habits that help
- Named imports:
import { format } from "date-fns". - Import from specific paths when a package lacks good ESM support.
- Avoid
import * as libcombined with dynamic access (lib[name]). - Be careful with large barrel files (
index.tsre-exporting everything); they can slow builds and sometimes keep extra code.
What it cannot remove
- Code that is used conditionally at runtime (it cannot know the condition).
- Side-effectful modules.
- Unused class methods or object properties in many cases.
Verify
Inspect the bundle with an analyzer, or check that removing an import changes the output size.
Code example
tsx
1// utils/math.ts2export function add(a: number, b: number) {3 return a + b;4}5export function hugeMatrixInverse(m: number[][]) {6 // imagine 50KB of code here7 return m;8}910// app.ts - only `add` is imported, so hugeMatrixInverse is dropped in production11import { add } from "./utils/math";12console.log(add(2, 3));1314// Prevents tree shaking: namespace import + dynamic access15// import * as math from "./utils/math";16// const fn = (math as Record<string, Function>)[userChoice];1718// package.json of a library that is safe to shake19// { "type": "module", "sideEffects": ["*.css"] }
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React set.