Tree Shaking & Code Splitting
Tree Shaking & Code Splitting
Section titled “Tree Shaking & Code Splitting”Topics Covered
Section titled “Topics Covered”- Tree Shaking — Dead code elimination with ES modules
- Code Splitting — Splitting bundles into smaller chunks
- Measuring Impact — Analyzing bundle size reductions
Tree Shaking
Section titled “Tree Shaking”Introduction
Section titled “Introduction”Tree shaking is dead code elimination — removing unused exports from JavaScript bundles. It relies on ES module’s static structure.
How It Works
Section titled “How It Works”// 📁 utils.jsexport function used() { return 'used'; }export function unused() { return 'never used'; }
// 📁 main.jsimport { used } from './utils.js';// 'unused' is removed during tree shaking 🎯Best Practices for Tree Shaking
Section titled “Best Practices for Tree Shaking”// ✅ ES modules (static analyzable)export const value = 42;
// ❌ CommonJS (cannot be tree-shaken)module.exports = { value: 42 };
// ✅ Import only what you needimport { map, filter } from 'lodash-es';
// ❌ Importing the whole libraryimport _ from 'lodash';
// ✅ Side-effect free modules// package.json: "sideEffects": falseCode Splitting
Section titled “Code Splitting”Introduction
Section titled “Introduction”Code splitting breaks your bundle into smaller chunks that can be loaded on demand, reducing the initial load size.
Entry Point Splitting
Section titled “Entry Point Splitting”// webpack/vite: multiple entry pointsmodule.exports = { entry: { main: './src/main.js', admin: './src/admin.js' }};Dynamic Splitting
Section titled “Dynamic Splitting”// Route-based splitting (most common)const Home = () => import('./routes/Home.js');const About = () => import('./routes/About.js');const Dashboard = () => import('./routes/Dashboard.js');
// Route: load on navigationasync function navigate(route) { switch (route) { case 'home': return (await Home()).default; case 'about': return (await About()).default; case 'dashboard': return (await Dashboard()).default; }}Vendor Splitting
Section titled “Vendor Splitting”// webpack: split vendor codeoptimization: { splitChunks: { cacheGroups: { vendor: { test: /[\\/]node_modules[\\/]/, name: 'vendors', chunks: 'all' } } }}Measuring Impact
Section titled “Measuring Impact”// Check bundle sizesconsole.log(`Initial bundle: ${bundleSize / 1024}KB`);console.log(`Lazy loaded chunk: ${chunkSize / 1024}KB`);
// After optimization// 200KB → 50KB initial + 50KB lazy = 75% reduction 🚀Summary
Section titled “Summary”| Technique | What It Does | Benefit |
|---|---|---|
| Tree Shaking | Removes unused code | Smaller bundles |
| Code Splitting | Splits into chunks | Faster initial load |
| Dynamic Import | Loads on demand | Lazy loading |
| Vendor Splitting | Separates library code | Better caching |