Hi

What is tree shaking and why do we need it?

May 2022
A simple guide to tree shaking in JavaScript

JavaScript being an interpreted language, we need to rely on build tooling such as webpack to provide the benefits a compiler would usually bring. One of these benefits, is tree shaking.


What is tree shaking?

Tree shaking is a technique that analyzes your code and removes all the functions that haven't been used.

Tree shaking is performed by build tools such as webpack. It checks all your code files, and checks all the dependencies you have imported are actually used.

Note that it is up to the library to allow this to happen; if the library doesn't support tree shaking, then it will import everything regardless.

Why do we need it?

Smaller bundle sizes. If our web bundle ends up 1MB, it will be faster to load than if it was 2MB.

There are definitely more important techniques when it comes to reducing bundle size, but tree shaking is a cool feature of modern build tools, so it is good to know about.

An Example

Lodash is one of my favorite JavaScript libraries. It is a small utility library for performing common tasks with arrays and other data types.

import _ from "lodash";

// Using the cloneDeep method - no tree shaking
_.cloneDeep();
import cloneDeep from "lodash/cloneDeep";

// Same method but with tree shaking
cloneDeep();

Many libraries support tree shaking through ES6 module destructuring like so:

import { cloneDeep } from "lodash";

Lodash doesn't currently support this, but supports tree shaking via separate directories for each function.


Tree shaking is a great technique to reduce bundle size. These things are important to know for all developers, but especially important if you are developing a public library.

Back to top

© 2025 alister.codes