Tree Shaking
ELI5 — The Vibe Check
Tree shaking is when your bundler looks at all the code you imported but never actually used, and throws it in the trash. Like if you imported an entire library of 1000 functions but only used 2 — tree shaking deletes the other 998 so users don't have to download them.
Real Talk
Tree shaking is a dead-code elimination technique used by bundlers (pioneered by Rollup) that statically analyzes ES module import/export statements to determine which code is actually used, and excludes unused exports from the final bundle. It requires ES modules (not CommonJS) to work effectively.
Show Me The Code
// utils.js — exports 3 functions
export const add = (a, b) => a + b
export const subtract = (a, b) => a - b
export const multiply = (a, b) => a * b
// main.js — only imports one
import { add } from './utils'
// Bundler removes subtract and multiply from output
When You'll Hear This
Tree shaking removed 80KB of unused lodash methods.,CommonJS modules break tree shaking — use ESM.,Check if your library is tree-shakeable before adding it.
Related Terms
Bundle
Imagine your code is a pile of LEGO instructions split across 50 tiny papers.
Bundler
A bundler is the robot that smashes all your separate JavaScript files, CSS, images, and random imports into one (or a few) neat packages that the browser...
Code Splitting
Instead of sending the user one massive JavaScript file for your entire app, code splitting lets you break it into chunks and only send what's needed for t...
Rollup
Rollup is the bundler you use when you're building a library rather than an app.
Vite
Vite is what happens when someone got sick of waiting 30 seconds for Webpack to start.