What is Tree Shaking?

Abhay Jain
2 min readJan 7, 2021

Tree shaking is a form of dead code elimination. The term was popularized by Rollup, but the concept of dead code elimination has existed for some time. The concept has also found purchase in webpack.

The term “tree shaking” comes from the mental model of your application and its dependencies as a tree-like structure. Each node in the tree represents a dependency that provides distinct functionality for your app. In modern apps, these dependencies are brought in via static import statements like so:

// Import all the array utilities!
import arrayUtils from "array-utils";

When your app is young (a sapling, if you will), you may have relatively few dependencies. You’re also using most (if not all) the dependencies you add. As your app ages, however, more dependencies can get added. To compound matters, older dependencies fall out of use, but may not get pruned from your codebase. The end result is that an app ends up shipping with a lot of unused JavaScript. Tree shaking addresses this by taking advantage of how we use static import statements to pull in specific parts of ES6 modules:

// Import only some of the utilities!
import { unique, implode, explode } from "array-utils";

The difference between this import example and the previous one is that rather than importing everything from the "array-utils" module (which could be a lot of stuff!), this example imports only specific parts of it. In dev builds, this doesn't really change anything, as the entire module gets imported regardless. In production builds, however, we can configure webpack to "shake" off exports from ES6 modules that weren't explicitly imported, making that production builds smaller.



Abhay Jain

Developer with 3 yrs of industrial experience in developing scalable web applications.