What is Tree Shaking?
Tree shaking, also known as live code inclusion, is a technique for optimizing code written in ECMAScript dialects like JavaScript. As apps accumulate dependencies over time, some of them are likely to fall out of use. The result is bloat, or messy code that wastes resources and drags down your application’s performance. The aim of tree shaking is to remove unused JavaScript to ensure that only executable code gets sent to the user. If you think of your application as a tree trunk and its dead dependencies as dead limbs, the analogy is quite clear.
Why Perform Tree Shaking?
JavaScript is significantly more expensive to process than other web resources, such as images and HTML, because it must be parsed and compiled prior to execution. That’s why web developers should strive to trim down their JavaScript code as much as possible before bundling it up. For example, the image below shows the execution time between 170KB worth of JavaScript versus a JPEG image that is 170KB in size.