Skip to main content
Web DevRendering & FrontendDiagramIntermediate

Tree Shaking

KO: 트리 셰이킹 (Tree Shaking)·EN: Tree Shaking·JA: ツリーシェイキング

A build-time dead-code elimination technique that analyzes static ES module imports and strips unused exports from the final bundle

Table of Contents

Structure Diagram

Static Module Graph Analysis & Dead-Code PruningTap a node
named impoReachableDead CodeEntry (en…utils Mod…formatDat…unusedFn(…
ROOTEntry (entry.ts)
1 link
Quick Answer

What is Tree Shaking?

A build-time dead-code elimination technique that analyzes static ES module imports and strips unused exports from the final bundle. It is a core concept in Rendering & Frontend within Web Dev.

Core Principles

Tree shaking is a form of dead-code elimination where bundlers (Rollup, Webpack, Vite, esbuild) statically walk the module dependency graph and drop any exports that are never imported or reachable from the application entry point.

It relies on the static structure of ES Modules (import/export), whose bindings are known at compile time. Legacy CommonJS (require()) is dynamic, making safe pruning far harder for bundlers.

Practical Takeaways

  • Declare "sideEffects": false in package.json: Telling the bundler that modules have no import-time side effects (or listing only CSS/polyfill files) unlocks aggressive pruning of unused re-exports.
  • Be careful with barrel files (index.ts): Re-exporting dozens of modules through a single barrel file often slows dev startup and can defeat tree shaking if any imported module has side effects.
  • Verify with a bundle analyzer: Prefer ESM-native packages (e.g., lodash-es over lodash) and inspect production chunks with rollup-plugin-visualizer or @next/bundle-analyzer.

Notable Examples

  • Utility and icon libraries: Importing 3 helpers from a 200-function ESM package ships only those 3 functions in production.
  • Production dead-branch elimination: Stripping dev-only assertions (NODE_ENV !== 'production') alongside unused feature modules during minification.