Tree shaking is a build step that removes code your site imported but never actually runs, so the JavaScript sent to visitors is as small as it can be. The name comes from the idea of shaking a tree and letting the dead leaves fall, leaving only the live branches.

Here is a practical example. You pull in a date library to use one small function, but the library also contains dozens of others you never touch. Without tree shaking all of it would be shipped. With it, the bundler traces what your code genuinely reaches, keeps that, and drops the rest. This works best when JavaScript libraries are written with standard import and export statements, which let the tool follow the trail cleanly.

It has limits worth knowing. If a library still uses the older CommonJS require style, or if importing a file quietly changes a global setting, the tool cannot always prove the code is safe to remove, so it keeps it to be safe. That is why a vague import * as utils often ships more than naming the one function you want. Some libraries help by marking themselves side-effect free in their package settings, which tells the bundler it can drop unused parts with confidence.

The benefit is straightforward: a smaller download means a faster page, which matters most on slower mobile connections. Tree shaking usually runs automatically in tools like Vite and Rollup, and it pairs with techniques like code splitting to keep what reaches the browser to a minimum.

At TopDevs we lean on tree shaking and modern bundlers so client sites only ship the code they use, keeping load times short.