Tree-shaking and Code Splitting
Tree-shaking and Code Splitting in Module System
In modern JavaScript, it's crucial to create small and optimized bundles. To make your projects load faster and more efficient, two important techniques are used: Tree-shaking and Code Splitting.
These techniques are primarily applied with ES Modules and Module Bundlers (like Webpack, Rollup):
Tree-shaking is a process that removes unused code (dead code) from your application. This makes the final bundle smaller and more efficient.
For example, if you only import one function, the remaining unused functions won't be included in the final file.
// utils.js
export function sum(a, b) {
return a + b;
}
export function multiply(a, b) {
return a * b;
}
// main.js
import { sum } from './utils.js';
console.log(sum(2, 3)); // 5
If the bundler supports tree-shaking, only the sum
function will remain in the bundle, while the multiply
function will be removed.
Conditions for tree-shaking to work:
import
/export
), not CommonJS (require
).Code Splitting is a technique that divides your code into smaller chunks that can be loaded on demand, rather than loading everything at once.
For example, if you have a large application, you can load only the main page code, and load other pages' code only when the user visits them.
// Regular import
import { heavyFunction } from './heavy-module.js';
heavyFunction();
// Dynamic import for Code Splitting
async function loadHeavyFunction() {
const { heavyFunction } = await import('./heavy-module.js');
heavyFunction();
}
loadHeavyFunction();
This way, heavy-module.js
will only load when needed.
There are three main types of Code Splitting:
Tree-shaking and Code Splitting have become essential tools in modern frontend development. They help create faster, lighter, and more user-friendly web applications. If you use ES Modules and structure your code properly, you can fully benefit from these techniques.