EasyBundle Optimization📖 Theory Question

What is tree shaking and what conditions must be met for it to work?

💡

Hint

Dead code elimination via static analysis of ES module imports — requires ESM, no side-effect imports, no CommonJS

Full Answer

Tree shaking is the process of removing unused exports from a bundle by statically analyzing which imports are referenced.

Conditions required:

  • ES Modules (ESM)import/export are statically analyzable. CommonJS require() is dynamic so bundlers can't determine what's used at build time.
  • sideEffects: false in package.json — tells the bundler it's safe to drop any module that isn't imported. Without this, bundlers assume every module might have side effects (e.g., polyfills modifying globals).
  • No dynamic import patternsimport(variable) defeats static analysis.
  • Bundler support — Webpack, Rollup, esbuild, Vite all support tree shaking by default for ESM.
// utils.ts — only 'add' is imported, 'multiply' will be shaken out
export function add(a: number, b: number) { return a + b; }
export function multiply(a: number, b: number) { return a * b; }

// index.ts
import { add } from './utils'; // multiply never bundled
💡 Common mistake: importing from a barrel file (import { Button } from '@ui') can defeat tree shaking if the barrel re-exports from CommonJS modules. Prefer deep imports for large libraries.

More Bundle Optimization Questions

EasyWhat is code splitting and how does dynamic import() enable it?EasyHow do you analyze and diagnose large bundle sizes?EasyWhat is vendor chunk splitting and why is it important for caching?MediumWhat is the module/nomodule pattern for differential serving?

Practice this in a timed sprint →

5 free questions, no signup required

⚡ Start Sprint