Performance

What is Tree Shaking?

Tree shaking is a JavaScript optimization technique that eliminates unused code (dead code) from the final bundle during the build process. By analyzing module imports and exports, tree shaking removes functions and variables that are never actually used, reducing bundle size.

How Does Tree Shaking Work?

Tree shaking relies on the static structure of ES module syntax (import/export) to determine which exports from a module are actually consumed by the application. During bundling, tools like Webpack, Rollup, and esbuild trace the dependency graph from entry points and mark unreachable code for removal. For example, if you import only one function from a utility library, tree shaking removes all the other unused functions from the final bundle.

Effective tree shaking can dramatically reduce JavaScript bundle sizes, directly improving page load performance and Time to Interactive. For tree shaking to work optimally, libraries must use ES module syntax rather than CommonJS (require), and side effects must be properly declared in package.json. The sideEffects field tells the bundler which files have side effects that should not be removed. Modern frameworks like Next.js and Vite have tree shaking enabled by default in production builds, automatically eliminating dead code to deliver the smallest possible bundles to users.