Tree-shaking 101
I spent a significant amount of time at work these last few months exploring tree-shaking and finding that it wasn't nearly as easy as I thought. We have been trying to build a simple UI library and wanted to get it to tree-shake to prevent consumers from importing the whole thing when putting a button on the page. As a team, we thought this would be pretty simple, but it turned out we were wrong...
In this post, I want to share my findings to spare you the same pain I went through and hopefully save yourself some time too.
What is tree-shaking?
Simply put, tree-shaking is the act of analysing code at build time and removing anything that will not get executed. It is not unique to the JavaScript/TypeScript universe, but I will be coming at it from that angle, as it is what I have experience with. Interestingly, the concept has been around since the 1990s according to Wikipedia, when it was first used in LISP.
However, the term "tree-shaking" as we know it was coined by the team behind Rollup, a bundler that is renowned for its tree-shaking abilities. You can think of the codebase as a tree, and when it is "shaken" (bundled) the dead leaves (bits of code that will not get executed) fall off, making the codebase leaner.
