Software Tidbit #6 - Tree Shaking
In a nutshell - it means removing unused code from your bundle, AKA dead-code elimination. It’s a cool process that helps reduce your bundle size, but there are a few caveats.
For example, code with potential side effects cannot be “shaken”, and bundlers are still not as smart as they could be. In the case of Webpack, one thing we can do to help shake the tree is to provide the bundler’s compiler with the “sideEffects” attribute in our package.json file. Assuring it that our module has no side effects.
{
"name": "my-pure-module",
"sideEffects": false
}
Alternatively, if our module does have side effects, we can explicitly list the module’s dependencies.
{
"name": "my-unpure-abomination-module",
"sideEffects": ["./file-with-side-effects"]
}
Some cases, however, are a bit more interesting.
Let’s have a look at closures. They might have a specific reference - in the case of listeners - the DOM element they are attached to. But they might close over code that might never be called. Which will essentially introduce unused code into our bundle.
Luckily, there are solutions for this too. One of them is the Qwik framework which I’ll discuss in my next article, stay tuned :)
Read more here: https://webpack.js.org/guides/tree-shaking/