Let us try to understand what is Tree shaking in JavaScript and how it helps.
Performance is the key to any successful web application, the user wants everything to be loaded fast and developers are relentlessly trying to make the application faster by applying different performance optimization techniques.
Tree shaking also known as unused exports is a process of removing unused code from the JavaScript bundles.
The term Tree shaking was popularized by Rollup and it was later adopted by Webpack. Both of these are popular bundlers that help you to bundle your javascript files and create a production build that you can use.
It is extremely important to keep the production build as light as possible so that it will be downloaded, processed and executed faster.
According to a 2018 survey, the average javascript bundle size on mobile devices was 350kb compressed, when uncompressed we will get around 800kb to 900kb file.
After transferring the 350kb compressed file, it will be uncompressed, parsed, and compiled in the browser which is an expensive thing for performance.
With the emergence of modern JavaScript frameworks, the focus of developers are shifted to creating applications in less time and the component-based development architecture has led to the creation of multiple files.
The logic is now abstracted to separate files and imported as and when required, though this has solved lots of issues but it has also given rise to new problems.
Each component can have unused code that the other component may not require, or it may not be used anywhere in the whole application, but when included it will increase the build size, ultimately affecting the performance.
For example, let's say we have this utility file that holds different utility functions.
// utility.js
export function foo() {
console.log("I am foo");
}
export function bar() {
console.log("I am bar");
}
Now import the function foo in another file.
// main.js
import { foo } from './utility.js'
foo();
Assuming that were are here using Webpack as a bundler and that too in the development mode.
In the final build, you will see something like,
/* 1 */
/***/ (function (module, __webpack_exports__, __webpack_require__) {
'use strict';
/* unused harmony export bar */
/* harmony export (immutable) */ __webpack_exports__['a'] = foo;
function bar() {
console.log("I am bar");
}
function foo() {
console.log("I am foo");
}
});
Even though we are not using the bar function it is included in the final build and it is annotated by the comment /* unused harmony export bar */ stating this is an unused function.