What is tree shaking?

JavaScript Performance ImportantGoogleNetflix

Tree Shaking

It can happen that we add code to our bundle that isn’t used anywhere in our application. This piece of dead code can be eliminated in order to reduce the size of the bundle, and prevent unnecessarily loading more data! The process of eliminating dead code before adding it to our bundle, is called tree-shaking.

Example

Let's say we have a file called math.js that contains four functions: add, subtract, multiply, and divide. Now, we only need the add function in our application.

// math.js
export const add = (a, b) => a + b;
export const subtract = (a, b) => a - b;
export const multiply = (a, b) => a b;
export const divide = (a, b) => a / b;
// index.js
import { add } from './math.js';
console.log(add(5, 3)); // 8

With tree shaking enabled, the final bundle will only include the add function. The subtract, multiply, and divide functions will be "shaken off" since they're not being used, resulting in a smaller bundle size.

Without tree shaking, all functions would be included in the bundle, even though we're only using one of them.

Requirements for tree shaking

  • Only modules defined with the ES2015 module syntax (import and export) can be tree-shaken. The way you import modules specifies whether the module can be tree-shaken or not.
  • The bundler must be able to analyze the code and identify the parts that are not used. You can use a tool like Webpack or Rollup to enable tree shaking.

How does tree shaking work?

Tree shaking starts by visiting all parts of the entry point file with side effects, and proceeds to traverse the edges of the graph until new sections are reached. Once the traversal is completed, the JavaScript bundle includes only the parts that were reached during the traversal. The other pieces are left out.

In the context of tree shaking and JavaScript bundling, a "side effect" refers to code that does something beyond just exporting values - it modifies something outside its own scope or has an observable interaction with the outside world when executed.

00:00

Table of Contents