JavaScript and TypeScript course ยท Module 9: Design Patterns and Architecture
Code splitting and tree shaking
In this lesson11
In the world of modern web development, where applications are becoming increasingly complex, managing the size of JavaScript bundles is crucial for performance. Two fundamental optimization techniques - code splitting and tree shaking - allow us to drastically reduce the size of code delivered to users.
What is code splitting?
Code splitting is a technique of dividing code into smaller fragments (chunks) that can be loaded on demand (lazy loading) or in parallel. Instead of sending all the application code in one large bundle, we can divide it into logical parts and load only what we currently need.
Problems solved by code splitting
// Problem: One huge bundle
// main.bundle.js (2.5MB)
// - Homepage code (200KB)
// - Admin panel code (800KB)
// - Online store code (1.5MB)
// A user viewing only the homepage unnecessarily downloads 2.3MB of code!
// Solution: Code splitting
// main.bundle.js (200KB) - only homepage code
// admin.chunk.js (800KB) - loaded only when needed
// shop.chunk.js (1.5MB) - loaded only when neededTypes of code splitting
1. Route-based code splitting
The simplest and most commonly used type - splitting code by application routes:
// React Router with lazy loading
import { lazy, Suspense } from 'react';
import { Routes, Route } from 'react-router';
// Each component is a separate chunk
const HomePage = lazy(() => import('./pages/HomePage'));
const ProductPage = lazy(() => import('./pages/ProductPage'));
const AdminPanel = lazy(() => import('./pages/AdminPanel'));
function App() {
return (
<Suspense fallback={<div>Loading...</div>}>
<Routes>
<Route path="/" element={<HomePage />} />
<Route path="/product/:id" element={<ProductPage />} />
<Route path="/admin" element={<AdminPanel />} />
</Routes>
</Suspense>
);
}2. Component-based code splitting
Splitting code at the component level:
// Lazy loading individual components
const ExpensiveChart = lazy(() => import('./components/ExpensiveChart'));
const HeavyDataTable = lazy(() => import('./components/HeavyDataTable'));
function Dashboard({ showChart, showTable }) {
return (
<div>
<h1>Main panel</h1>
{showChart && (
<Suspense fallback={<div>Loading chart...</div>}>
<ExpensiveChart />
</Suspense>
)}
{showTable && (
<Suspense fallback={<div>Loading table...</div>}>
<HeavyDataTable />
</Suspense>
)}
</div>
);
}3. Dynamic imports
Importing code in response to user actions:
// Loading a library only when needed
async function showAdvancedEditor() {
// CodeMirror is loaded only when the user clicks the button
const { EditorView, basicSetup } = await import('codemirror');
const { javascript } = await import('@codemirror/lang-javascript');
const editor = new EditorView({
extensions: [basicSetup, javascript()],
parent: document.getElementById('editor-container')
});
}
// Event listener on button
document.getElementById('show-editor').addEventListener('click', showAdvancedEditor);4. Vendor code splitting
Separating external libraries from application code:
// webpack.config.js
module.exports = {
optimization: {
splitChunks: {
chunks: 'all',
cacheGroups: {
// External libraries in a separate chunk
vendor: {
test: /[\\/]node_modules[\\/]/,
name: 'vendors',
chunks: 'all',
},
// Common application code
common: {
name: 'common',
minChunks: 2,
chunks: 'all',
enforce: true
}
}
}
}
};What is tree shaking?
Tree shaking is the process of removing "dead code" - code that is not used in the application. The name comes from the metaphor of "shaking a tree", where only unnecessary leaves (unused code) fall off.
How does tree shaking work?
// utils.js - we export many functions
export function formatDate(date) {
return date.toLocaleDateString();
}
export function formatTime(date) {
return date.toLocaleTimeString();
}
export function formatCurrency(amount) {
return new Intl.NumberFormat('pl-PL', {
style: 'currency',
currency: 'PLN'
}).format(amount);
}
export function validateEmail(email) {
return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
}
// main.js - we import only what we need
import { formatDate, formatCurrency } from './utils.js';
// Tree shaking will remove formatTime and validateEmail from the final bundle
console.log(formatDate(new Date()));
console.log(formatCurrency(100));Requirements for tree shaking
- ES Modules (ESM) - tree shaking only works with ES6 modules:
// Works with tree shaking (ES modules)
import { specificFunction } from './module.js';
// Does not work with tree shaking (CommonJS)
const { specificFunction } = require('./module.js');- Static imports - imports must be static:
// Static import - tree shaking works
import { debounce } from 'lodash-es';
// Dynamic import - tree shaking does not work
const moduleName = 'lodash-es';
import(moduleName).then(module => {
const { debounce } = module;
});- Named exports - prefer named exports over default exports:
// Named exports - better for tree shaking
export const add = (a, b) => a + b;
export const subtract = (a, b) => a - b;
// Default export with object - worse for tree shaking
export default {
add: (a, b) => a + b,
subtract: (a, b) => a - b
};Practical optimization examples
CSS library optimization
// Importing the entire Bootstrap library
import 'bootstrap/dist/css/bootstrap.css';
// Importing only needed modules (your own SCSS file)
import './bootstrap-custom.scss';// bootstrap-custom.scss (Bootstrap 5): Sass partials are imported from SCSS, not from JavaScript
@import 'bootstrap/scss/functions';
@import 'bootstrap/scss/variables';
@import 'bootstrap/scss/variables-dark';
@import 'bootstrap/scss/maps';
@import 'bootstrap/scss/mixins';
@import 'bootstrap/scss/utilities';
// Keep only display (d-*), margin (m-*) and padding (p-*) classes
$utilities: map-get-multiple($utilities, ('display', 'margin', 'padding'));
@import 'bootstrap/scss/utilities/api';JavaScript library optimization
// Importing the entire Lodash library (>70KB)
import _ from 'lodash';
const result = _.debounce(handleSearch, 300);
// Importing only the needed function from lodash-es
import { debounce } from 'lodash-es';
const result = debounce(handleSearch, 300);
// Or even better - single function
import debounce from 'lodash-es/debounce';
const result = debounce(handleSearch, 300);Tree shaking in React
// Namespace import - with static access (MUI.Button) the bundler still drops unused components
import * as MUI from '@mui/material';
// Importing only needed components
import { Button, TextField, Card } from '@mui/material';
// Or individual imports
import Button from '@mui/material/Button';
import TextField from '@mui/material/TextField';
import Card from '@mui/material/Card';Bundler configuration
Webpack
// webpack.config.js
module.exports = {
mode: 'production', // Enables tree shaking automatically
optimization: {
usedExports: true, // Marks used exports
sideEffects: true, // Honors the "sideEffects" field in package.json (default in production mode)
splitChunks: {
chunks: 'all',
cacheGroups: {
vendor: {
test: /[\\/]node_modules[\\/]/,
name: 'vendors',
chunks: 'all',
}
}
}
}
};Vite
// vite.config.js - Vite 8+ (Rolldown); in Vite 7 and older: build.rollupOptions.output.manualChunks
import { defineConfig } from 'vite';
export default defineConfig({
build: {
rolldownOptions: {
output: {
codeSplitting: {
groups: [
{ name: 'vendor', test: /[\\/]node_modules[\\/](react|react-dom)[\\/]/ },
{ name: 'utils', test: /[\\/]node_modules[\\/](lodash-es|date-fns)[\\/]/ }
]
}
}
}
}
});Rollup
// rollup.config.js
export default {
input: 'src/main.js',
output: {
dir: 'dist',
format: 'es',
manualChunks: (id) => {
if (id.includes('node_modules')) {
return 'vendor';
}
}
},
external: ['react', 'react-dom']
};Advanced techniques
Preloading and prefetching
// Preload - high priority, needed immediately
const AdminPanel = lazy(() =>
import(/* webpackPreload: true */ './AdminPanel')
);
// Prefetch - low priority, likely needed later
const UserProfile = lazy(() =>
import(/* webpackPrefetch: true */ './UserProfile')
);Bundle analysis
The webpack-bundle-analyzer plugin writes an HTML report with a map of the bundle on every build: each module is a rectangle whose area is proportional to its size, so you can see right away what takes up the most space:
// Bundle analysis using webpack-bundle-analyzer
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
module.exports = {
plugins: [
new BundleAnalyzerPlugin({
analyzerMode: 'static',
openAnalyzer: false,
generateStatsFile: true
})
]
};Custom loading strategies
You can also pick the version of a component based on the connection quality reported by the Network Information API (navigator.connection). It works only in Chromium-based browsers, so in the others the code picks the lighter version:
// Loading strategy based on internet connection
async function loadComponentBasedOnConnection() {
const connection = navigator.connection || navigator.mozConnection || navigator.webkitConnection;
if (connection && connection.effectiveType === '4g') {
// Fast connection - load full version
return import('./components/FullFeaturedComponent');
} else {
// Slow connection - load simplified version
return import('./components/LightweightComponent');
}
}Side effects and package.json
The sideEffects field in a library's package.json tells the bundler whether its modules have side effects. The value false means that no file has any, so the bundler can skip a module you import nothing from entirely:
{
"name": "my-library",
"version": "1.0.0",
"sideEffects": false,
"main": "dist/index.js",
"module": "dist/index.esm.js"
}Files with side effects that the bundler must keep are listed in an array:
{
"sideEffects": [
"src/polyfills.js",
"src/global-styles.css",
"**/*.css"
]
}Practical tips
1. Monitoring bundle size
Before you add a library to the project, check how much it weighs after minification and after gzip compression:
# Using bundlephobia to check library size
npm install -g bundle-phobia-cli
bundle-phobia lodash
bundle-phobia lodash-es2. Webpack Bundle Analyzer
npm install --save-dev webpack-bundle-analyzer
npx webpack --profile --json=stats.json
npx webpack-bundle-analyzer stats.json3. Lighthouse CI for monitoring
# .github/workflows/lighthouse.yml
- name: Lighthouse CI
run: |
npm install -g @lhci/cli
lhci autorunFull optimization example
// Before optimization
import React from 'react';
import * as MUI from '@mui/material';
import _ from 'lodash';
import moment from 'moment';
import './styles.css';
function App() {
const [users, setUsers] = React.useState([]);
const debouncedSearch = _.debounce((query) => {
// Search users
}, 300);
return (
<MUI.Container>
<MUI.TextField onChange={(e) => debouncedSearch(e.target.value)} />
{users.map(user => (
<MUI.Card key={user.id}>
<MUI.Typography>
{user.name} - {moment(user.createdAt).format('DD/MM/YYYY')}
</MUI.Typography>
</MUI.Card>
))}
</MUI.Container>
);
}// After optimization
import React, { useState, lazy, Suspense } from 'react';
import { Container, TextField } from '@mui/material';
import { debounce } from 'lodash-es';
import { format } from 'date-fns';
import { pl } from 'date-fns/locale';
// Lazy loading for rarely used components
const UserCard = lazy(() => import('./components/UserCard'));
function App() {
const [users, setUsers] = useState([]);
const debouncedSearch = debounce((query) => {
// Search users
}, 300);
return (
<Container>
<TextField onChange={(e) => debouncedSearch(e.target.value)} />
<Suspense fallback={<div>Loading...</div>}>
{users.map(user => (
<UserCard
key={user.id}
name={user.name}
date={format(new Date(user.createdAt), 'dd/MM/yyyy', { locale: pl })}
/>
))}
</Suspense>
</Container>
);
}Benefits and results
Bundle size savings
- Lodash: 70KB -> 2KB (single function)
- Moment.js: 230KB -> 11KB (date-fns)
- Material-UI: 1.2MB -> 200KB (only used components)
- Bootstrap: 150KB -> 30KB (only needed modules)
Performance impact
// Performance metrics
const performanceMetrics = {
beforeOptimization: {
bundleSize: '2.5MB',
firstContentfulPaint: '3.2s',
largestContentfulPaint: '4.8s',
timeToInteractive: '5.2s'
},
afterOptimization: {
bundleSize: '450KB',
firstContentfulPaint: '1.1s',
largestContentfulPaint: '1.8s',
timeToInteractive: '2.1s'
}
};Summary
Code splitting and tree shaking are fundamental optimization techniques for modern web applications. They allow you to:
- Reduce initial bundle size - users download only the code needed for the first render
- Speed up loading time - smaller files = faster downloads
- Improve User Experience - the application runs faster and smoother
- Save data transfer - especially important on mobile devices
- Enable better caching - vendor libraries change rarely
The key to success is a systematic approach: regular bundle audits, library size monitoring, and conscious decisions about what dependencies we add to the project.
In the editor below you will calculate, on sample data, how many kilobytes a visitor saves at startup thanks to code splitting and tree shaking.
Code for this lesson: index.js
// Code splitting and tree shaking in numbers: a simulation of the Jurassic Park bundle
// Change the data below and watch how many kilobytes a visitor downloads at startup.
// static = a regular import (the module goes into the initial bundle)
// dynamic = import('./file.js') (the bundler moves it into a separate chunk downloaded on demand)
const modules = [
{ file: 'app.js', kb: 45, load: 'static' },
{ file: 'park-map.js', kb: 120, load: 'static' },
{ file: 'admin-panel.js', kb: 310, load: 'dynamic' },
{ file: 'genetics-charts.js', kb: 180, load: 'dynamic' },
];
const totalKb = (list) => list.reduce((sum, m) => sum + m.kb, 0);
const initial = modules.filter((m) => m.load === 'static');
const chunks = modules.filter((m) => m.load === 'dynamic');
console.log('Without code splitting at startup:', totalKb(modules), 'kB');
console.log('With code splitting at startup:', totalKb(initial), 'kB');
console.log('Chunks downloaded on demand:', chunks.map((m) => m.file + ' (' + m.kb + ' kB)').join(', '));
// Tree shaking: only the exports you import go into the bundle (sizes in kB)
const parkUtils = { formatDate: 2, debounce: 3, deepClone: 6, chartEngine: 95 };
const imported = ['formatDate', 'debounce'];
const libraryKb = Object.values(parkUtils).reduce((sum, kb) => sum + kb, 0);
const shakenKb = imported.reduce((sum, name) => sum + parkUtils[name], 0);
console.log('Whole library:', libraryKb, 'kB');
console.log('After tree shaking:', shakenKb, 'kB');
// Try it: change the load of park-map.js to 'dynamic' or add 'chartEngine' to imported.Docs entries used in this lesson
Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. What characterizes a pure function?
2. What is immutable state?
These are 2 of 4 questions for this lesson. Solve the rest in the game.
Hands-on tasks in the game
- Vertical ordering
Arrange the steps for implementing immutable state:
- Code editor
The index.html file has a #park-app container and a script with the ParkInterface class, which builds the park dashboard from the parkData data (the look of the panels is in style.css). Fill in the blanks: ___BLANK1___ is the array method that turns every dinosaur into a string with an <li> element, ___BLANK2___ is the array method that joins these strings into one (without commas between them), and ___BLANK3___ is the element property through which render() inserts the finished HTML into the container. After the page runs, #park-app should contain three .panel panels with h2 headings, the first one with a list of all dinosaurs; render() should also work for another container and other data.
- Click in order
Arrange the elements of the Factory pattern:
- Code editor
The index.js file has a TimeSimulation class. Fill in the blanks: ___BLANK1___ is the number of hours in a day, after which the hour counter goes back to 0 (tick() after 23:00 gives 0:00 and the next day), ___BLANK2___ is the logical operator in isNight(), because the night is the hours from 20 to 23 and from 0 to 5, and ___BLANK3___ is the browser function that calls tick() every intervalMs milliseconds until clearInterval. A second call to start() must not start a second loop, and stop() stops it.