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 };
But, you only imported adder
:
import { adder } from "./utils";
adder(1, 2);
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);
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 };
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);
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
If you are looking at this you probably wonder who I am; teenage open source maintainer