What Is Tree Shaking post image

What Is Tree Shaking

We are used to using modules in JavaScript (aka esm ) since ES6 (or ES2015) ECMAScript modules are the official standard format for packing JavaScript code for reuse. In applications with multiple modules it’s constant to have functions, methods, variables and many others pieces of code not used in our apps.

The tree shaking term in the JavaScript world refers to dead-code elimination from our application, the name became popular with Rollup — an ES2015 module bundler. Tree shaking is a technique that statically analyzes the code that is imported from some module and during the bundle removes unused codes. This step is very important when we are going to prepare a production build, generating smaller files.

Tools like Webpack or the Rollup mentioned above detect these codes that are not being used in the application and remove them from the package generated.

Nice, but what is actually considered a dead code?

This answer is simple, we will use the Webpack as module bundle in our exemple, it is the code that Webpack does not see you using around the application, it’ll follow the trail of imports and exports throughout our app, if it finds any imported module that does not being used in the module that imported it, the Webpack will consider it as “dead code”.

Let’s see an example

math.ts
export function sum(a: number, b: number): number {
  return a + b;
}

export function minus(a: er, b: number): number {
  return a - b;
}
main.ts
import { sum, minus } from "./math";

const main = () => {
  console.log(sum(2, 2));
};

main();

The code snippet above will only add the Lodash map function to our build, not Lodash entirely. Using the tree shaking technique and eliminating dead code can significantly reduce the size of the code we have in our application.

Another technique that we can use is using the website BundlePhobia, which brings several details of a package published in NPM, such as the subject of this article - tree shaking.

Example of a package with tree shaking support (note the tree icon below the package name):

Bundlephobia with tree shaking

Example of a package without tree shaking support (without the tree icon below the package name):

Bundlephobia without tree shaking

We can improve the identification of dead code using lint tools, for example ESLint or TSLint. I’ll indicate the ESLint Plugin unused imports eslint-plugin-unused-imports - npm that will help you to identify unnecessary imports when you are coding.

Well, I hope I helped you to demystify this term that we hear a lot when we are using modules in JavaScript.

References: