DEV Community

Cover image for What is ES6 Tree Shaking
shadowtime2000
shadowtime2000

Posted on • Updated on • Originally published at h.shadowtime2000.com

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.

Top comments (6)

Collapse
 
ben profile image
Ben Halpern

Nice post

Collapse
 
bravemaster619 profile image
bravemaster619

Since @ben liked it, I assume this post will be selected as one of top posts in the week

Collapse
 
ben profile image
Ben Halpern

I suspect this post will at least be a longterm important page for folks coming from search engines. ๐Ÿ˜„

Collapse
 
shadowtime2000 profile image
shadowtime2000

Thanks!

Collapse
 
aidenybai profile image
Aiden Bai

Really well written. Wondering maybe as a call to action you could include some popular bundlers that support tree shaking at the end of the article

Collapse
 
machineno15 profile image
Tanvir Shaikh

Thanks, something new to learn ..