Today I am here with a topic in JavaScript called “Tree Shaking”. Feels interesting, right?!
It’s important to clear the space once we are done with our work and organize our stuff neatly, correct?
In the same way, in JavaScript, it’s important to clear or optimize unused code, and the code is no longer needed during the bundling process. This results in the most efficient and smaller code for the production. This process is called “Tree Shaking”.
Tools like ‘webpack’ identify unused or dead code, and webpack has minifiers, which are plugins that eliminate or remove the dead code while bundling.
Things to take care of to achieve Tree shaking:
1. Webpacks configuration file
We would have the webpack’s configuration file as below.
// Webpack Config for Tree Shaking
const config = {
mode: 'production',
optimization: {
usedExports: true,
minimizer: [
// Add required plugins here
]
}
};
2. Use ES6 JavaScript code
Tree shaking works when we use the ES6 module because ES6 code is syntactically analyzable.
The below code shows an example:
In the codesample.js file we have.
export function add(a, b) {
return a + b;
}
export function multiply(a, b) {
return a * b;
}
export function subtract(a, b) {
return a - b;
}
And in my main.js, I have
import {add} from './codesample.js'
console.log(add(5, 10));
So, here, we have used only functions from the codesample.js file, and multiply and subtract functions are not used. So, these unused codes are removed during the bundling process.
3. Side Effects
While doing minification, we can exclude some files from the removal of dead codes in terms of necessity, like we need that particular code for cross-browser compatibility(for example, when we have to use polyfills)
Example
In the package.js file, we could mention about the side effects below:
// All the files have side effects, so none of the files can be used for tree shaking.
{
"sideEffects": true
}
// There are no side effects, so all files can undergo tree shaking.
{
"sideEffects": false
}
// Only the below-mentioned files have side effects; all other files can undergo tree shaking.
// These specific files will be kept as they are.
{
"sideEffects": [
"./myjsfile1.js",
"./myjsfile2.js"
]
}
Tree shaking can remove unused code from third-party libraries as well if the code is written in ES6 standard. Tree shaking is a powerful concept as minimized, efficient, and cleaner code helps to run the application faster. I hope this article helps you to understand the topic!
Please follow the links for information on Accessibility, Cross-browser compatible applications, and the Local Override method on the C# Corner.