What is ES6 Tree Shaking

shadowtime2000

shadowtime2000

Posted on December 2, 2020

What is ES6 Tree Shaking

What is ES6 Tree Shaking

ES6 tree shaking is a way to optimize the bundle size of your bundle by removing everything that is guaranteed to not be used ever in the app. Let's give an example.

Let's say you have this util file:

function adder(a, b) {
    return a + b;
}
function subber(a, b) {
    return a - b;
}
export { adder, subber };
Enter fullscreen mode Exit fullscreen mode

But, you only imported adder:

import { adder } from "./utils";

adder(1, 2);
Enter fullscreen mode Exit fullscreen mode

Then it wouldn't make sense to include subber in the bundle too. So instead, through static analysis, it will kill subber because it is never used. Final bundle:

function adder(a, b) {
    return a + b;
}
adder(1, 2);
Enter fullscreen mode Exit fullscreen mode

But there are some problems. Let's say you have this:

function adder(a, b) {
    return a + b;
}
function subber(a, b) {
    return a - b;
}
window.subadd = (a, b) => (b, c) => adder(a, b) + subber(b, c);
export { adder, subber };
Enter fullscreen mode Exit fullscreen mode

This would be the final bundle:

function adder(a, b) {
    return a + b;
}
function subber(a, b) {
    return a - b;
}
window.subadd = (a, b) => (b, c) => adder(a, b) + subber(b, c);
adder(1, 2);
Enter fullscreen mode Exit fullscreen mode

Wow, that's including a lot of unnecessary code! The problem is, because of how Javascript works, you can dump side effects into a global namespace, and it will get included along with it's dependencies because it isn't guaranteed to never be used.

Supporting Full Tree Shaking (For Library Authors)

Of course, there is a way to support full tree shaking, without any risk of side effects. You first, need to kill all side effects in your package. Then, in your package.json, you set sideEffects: false. That will signify to the bundler that there are no side effects meaning you can fully tree shake it.

💖 💪 🙅 🚩
shadowtime2000
shadowtime2000

Posted on December 2, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

What is ES6 Tree Shaking
javascript What is ES6 Tree Shaking

December 2, 2020