JavaScript and TypeScript course ยท Module 9: Design Patterns and Architecture
Bundle optimization - analysis and package optimization
In this lesson9
Imagine a truck that delivers one bag of feed to the park while dragging a whole warehouse behind it, because nobody checked the cargo. Bundle optimization is a comprehensive process of analyzing and optimizing JavaScript packages: a smaller size, faster loading and efficient use of browser resources. It is the last step after code splitting, tree shaking and lazy loading.
Why does it matter?
The numbers below are a hypothetical example, not research results, but they show what we measure:
// Hypothetical example: illustrative numbers, not measurements
// Performance metrics before optimization
const beforeOptimization = {
bundleSize: '2.8MB',
firstContentfulPaint: '3.4s',
largestContentfulPaint: '5.1s',
timeToInteractive: '6.2s',
cumulativeLayoutShift: 0.25
};
// Performance metrics after optimization
const afterOptimization = {
bundleSize: '420KB',
firstContentfulPaint: '0.9s',
largestContentfulPaint: '1.6s',
timeToInteractive: '2.1s',
cumulativeLayoutShift: 0.05
};
// Performance improvement
const improvement = {
bundleSizeReduction: '85%',
fcpImprovement: '73%',
lcpImprovement: '69%',
ttiImprovement: '66%',
clsImprovement: '80%'
};
// Business impact cost analysis
const businessImpact = {
conversionRate: {
before: '2.1%',
after: '3.8%',
improvement: '+81%'
},
bounceRate: {
before: '68%',
after: '42%',
improvement: '-38%'
},
mobileUsersLost: {
before: '35%', // Due to slow loading
after: '12%',
improvement: '-66%'
},
revenueImpact: {
monthlyLoss: '$24,000', // Due to slow bundles
monthlyGain: '$45,000' // After optimization
}
};Of these metrics, LCP and CLS belong to the Core Web Vitals (the third one is INP), FCP is a supporting metric, and since Lighthouse 10 TTI no longer counts toward the score. Always measure your own numbers.
Bundle analysis tools
You introduce code splitting in four steps: analyzing the bundle size, choosing split points, configuring dynamic imports and verifying that chunks load as planned.
Webpack Bundle Analyzer
Webpack Bundle Analyzer draws a map of modules and shows which ones take up the most space:
# Installation and usage
npm install --save-dev webpack-bundle-analyzer
# Generate report (the analyzer reads the webpack stats file)
npx webpack --profile --json=stats.json
npx webpack-bundle-analyzer stats.json
# Integration with webpack config
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
module.exports = {
plugins: [
new BundleAnalyzerPlugin({
analyzerMode: 'static',
openAnalyzer: false,
generateStatsFile: true,
reportFilename: 'bundle-report.html'
})
]
};The analyzer reads the webpack stats file (stats.json), not the finished .js files.
Analysis in CI/CD
A GitHub Actions workflow checks the size on every push and pull request:
# .github/workflows/bundle-analysis.yml
name: Bundle Analysis
on: [push, pull_request]
jobs:
analyze:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '22'
- name: Install dependencies
run: npm ci
- name: Build and analyze
run: |
npm run build
npx size-limit
- name: Upload bundle stats
uses: actions/upload-artifact@v4
with:
name: bundle-stats
path: dist/stats.jsonnpx size-limit (with the size-limit and @size-limit/file packages in devDependencies) fails the build when a file exceeds its limit from package.json.
Source Map Explorer
Source Map Explorer shows which source files make up the finished bundle:
# Source map analysis
npm install --global source-map-explorer
# Analyze specific bundle
source-map-explorer bundle.js bundle.js.map
# HTML report (keep it to compare with the next version)
source-map-explorer bundle.js --html report.htmlThere is no built-in version comparison, so keep the HTML reports between releases.
Webpack Dashboard
Webpack Dashboard turns the raw webpack log into a readable panel in the terminal:
// Interactive dashboard during development
const DashboardPlugin = require('webpack-dashboard/plugin');
module.exports = {
plugins: [
new DashboardPlugin()
]
};The panel appears when you run webpack through the package's CLI, e.g. webpack-dashboard -- webpack --watch. Then you see the module sizes with every change.
Advanced optimization techniques
Dynamic chunking strategies
splitChunks divides node_modules into groups (cache groups) that the browser caches independently of the application code:
// webpack.config.js - Advanced chunk configuration
module.exports = {
optimization: {
splitChunks: {
chunks: 'all',
minSize: 20000,
maxSize: 244000,
cacheGroups: {
// Framework chunks (React, Angular, Vue)
framework: {
test: /[\\/]node_modules[\\/](react|react-dom|@angular|vue)[\\/]/,
name: 'framework',
priority: 40,
enforce: true
},
// UI Libraries chunk
ui: {
test: /[\\/]node_modules[\\/](@mui|antd|bootstrap|@chakra-ui)[\\/]/,
name: 'ui-libs',
priority: 30,
enforce: true
},
// Utility libraries chunk
utils: {
test: /[\\/]node_modules[\\/](lodash|ramda|date-fns|moment)[\\/]/,
name: 'utils',
priority: 20,
enforce: true
},
// Common application code
common: {
name: 'common',
minChunks: 2,
priority: 10,
reuseExistingChunk: true
},
// Large libraries in separate chunks
largeDeps: {
test: /[\\/]node_modules[\\/](monaco-editor|three|d3)[\\/]/,
name(module) {
const packageName = module.context.match(/[\\/]node_modules[\\/](.*?)([\\/]|$)/)[1];
return `lib.${packageName.replace('@', '')}`;
},
priority: 35,
enforce: true
}
}
}
}
};A higher priority wins when groups conflict, and enforce: true ignores the size thresholds. After a change in your own code, the user does not download React again.
Module Federation for micro-frontends
Module Federation, built into webpack 5, lets independent applications share code at runtime:
// webpack.config.js - Host application
const { ModuleFederationPlugin } = require('webpack').container;
module.exports = {
plugins: [
new ModuleFederationPlugin({
name: 'host',
filename: 'remoteEntry.js',
remotes: {
userDashboard: 'userDashboard@http://localhost:3001/remoteEntry.js',
productCatalog: 'productCatalog@http://localhost:3002/remoteEntry.js',
paymentSystem: 'paymentSystem@http://localhost:3003/remoteEntry.js'
},
shared: {
react: {
singleton: true,
requiredVersion: '^19.0.0',
eager: true
},
'react-dom': {
singleton: true,
requiredVersion: '^19.0.0',
eager: true
}
}
})
]
};
// Micro-frontend - User Dashboard
const { ModuleFederationPlugin } = require('webpack').container;
module.exports = {
plugins: [
new ModuleFederationPlugin({
name: 'userDashboard',
filename: 'remoteEntry.js',
exposes: {
'./UserProfile': './src/components/UserProfile',
'./UserSettings': './src/components/UserSettings'
},
shared: {
react: { singleton: true },
'react-dom': { singleton: true }
}
})
]
};singleton: true guarantees a single copy of React, and the two module.exports are two separate configuration files.
Incremental bundling
A disk cache speeds up later builds, because webpack rebuilds only what has changed:
// Webpack cache configuration for faster rebuilds
const path = require('path');
module.exports = {
cache: {
type: 'filesystem',
cacheDirectory: path.resolve(__dirname, '.webpack-cache'),
buildDependencies: {
config: [__filename],
tsconfig: [path.resolve(__dirname, 'tsconfig.json')],
packagejson: [path.resolve(__dirname, 'package.json')]
},
version: '1.0',
store: 'pack',
compression: 'gzip'
},
// Persistent cache for node_modules
snapshot: {
managedPaths: [path.resolve(__dirname, 'node_modules')],
buildDependencies: {
hash: true,
timestamp: true
},
module: {
timestamp: true
},
resolve: {
timestamp: true
}
}
};buildDependencies lists the files whose change invalidates the cache.
Budgets and monitoring
Budget configuration
A performance budget is a size limit that the size-limit tool reads from package.json:
{
"size-limit": [
{
"path": "./dist/js/main.*.js",
"limit": "170 kB",
"gzip": true
},
{
"path": "./dist/js/vendor.*.js",
"limit": "300 kB",
"gzip": true
},
{
"path": "./dist/css/*.css",
"limit": "50 kB",
"gzip": true
},
{
"path": "./dist/js/runtime.*.js",
"limit": "10 kB",
"gzip": true
}
]
}The limits apply to the gzipped size. Remove the first line, because JSON has no comments.
Automated performance monitoring
The monitor collects loading times from the Performance API for real users and compares them with thresholds:
// Performance monitoring service
class BundlePerformanceMonitor {
constructor() {
this.metrics = {
bundleSizes: new Map(),
loadTimes: new Map(),
cacheHitRates: new Map()
};
this.thresholds = {
maxBundleSize: 250000, // 250KB
maxLoadTime: 3000, // 3s
minCacheHitRate: 80 // 80%
};
}
async measureBundlePerformance() {
const performanceData = {
timestamp: Date.now(),
metrics: await this.collectMetrics(),
violations: this.checkViolations(),
recommendations: this.generateRecommendations()
};
await this.sendToMonitoring(performanceData);
return performanceData;
}
async collectMetrics() {
const bundleEntries = performance.getEntriesByType('navigation');
const resourceEntries = performance.getEntriesByType('resource');
return {
pageLoadTime: bundleEntries[0]?.loadEventEnd - bundleEntries[0]?.fetchStart,
resourceLoadTimes: resourceEntries
.filter(entry => entry.name.includes('.js') || entry.name.includes('.css'))
.map(entry => ({
name: entry.name,
size: entry.transferSize,
loadTime: entry.responseEnd - entry.fetchStart,
cached: entry.transferSize === 0
})),
memoryUsage: performance.memory ? {
used: performance.memory.usedJSHeapSize,
total: performance.memory.totalJSHeapSize,
limit: performance.memory.jsHeapSizeLimit
} : null
};
}
checkViolations() {
const violations = [];
// Check bundle sizes (transferSize from Resource Timing)
performance.getEntriesByType('resource')
.filter(entry => entry.name.includes('.js'))
.forEach(({ name: bundleName, transferSize: size }) => {
if (size > this.thresholds.maxBundleSize) {
violations.push({
type: 'SIZE_VIOLATION',
bundle: bundleName,
current: size,
threshold: this.thresholds.maxBundleSize,
severity: 'HIGH'
});
}
});
return violations;
}
generateRecommendations() {
const recommendations = [];
// Analyze duplicates in bundles
const duplicatedModules = this.findDuplicatedModules();
if (duplicatedModules.length > 0) {
recommendations.push({
type: 'REMOVE_DUPLICATES',
modules: duplicatedModules,
estimatedSavings: this.calculateDuplicateSavings(duplicatedModules)
});
}
// Analyze unused dependencies
const unusedDeps = this.findUnusedDependencies();
if (unusedDeps.length > 0) {
recommendations.push({
type: 'REMOVE_UNUSED_DEPS',
dependencies: unusedDeps,
estimatedSavings: this.calculateUnusedDepsSavings(unusedDeps)
});
}
return recommendations;
}
}
// Automatic monitoring in production
if (typeof window !== 'undefined' && process.env.NODE_ENV === 'production') {
const monitor = new BundlePerformanceMonitor();
// Measure after page load
window.addEventListener('load', () => {
setTimeout(() => {
monitor.measureBundlePerformance();
}, 2000);
});
}performance.memory exists only in Chromium, hence the check before using it. You write the helper methods (sendToMonitoring, findDuplicatedModules, findUnusedDependencies and the savings calculations) yourself.
Real User Monitoring (RUM)
PerformanceObserver reports every downloaded file and every long task:
// RUM for bundle performance
class RealUserBundleMonitoring {
constructor() {
this.sessionId = this.generateSessionId();
this.startTime = performance.now();
this.setupObservers();
}
setupObservers() {
// Performance Observer for resource timing
if ('PerformanceObserver' in window) {
const observer = new PerformanceObserver((list) => {
list.getEntries().forEach(entry => {
if (entry.name.includes('.js') || entry.name.includes('.css')) {
this.trackResourceLoad(entry);
}
});
});
observer.observe({ entryTypes: ['resource'] });
}
// Long task observer
if ('PerformanceObserver' in window) {
const longTaskObserver = new PerformanceObserver((list) => {
list.getEntries().forEach(entry => {
this.trackLongTask(entry);
});
});
longTaskObserver.observe({ entryTypes: ['longtask'] });
}
}
trackResourceLoad(entry) {
const resourceData = {
sessionId: this.sessionId,
timestamp: Date.now(),
resourceType: entry.name.includes('.js') ? 'javascript' : 'css',
resourceName: entry.name,
loadTime: entry.responseEnd - entry.fetchStart,
transferSize: entry.transferSize,
cached: entry.transferSize === 0,
userAgent: navigator.userAgent,
connectionType: navigator.connection?.effectiveType
};
this.sendMetric('resource_load', resourceData);
}
trackLongTask(entry) {
const longTaskData = {
sessionId: this.sessionId,
timestamp: Date.now(),
duration: entry.duration,
startTime: entry.startTime,
attribution: entry.attribution
};
this.sendMetric('long_task', longTaskData);
}
async sendMetric(type, data) {
// Send to analytics system
if (navigator.sendBeacon) {
navigator.sendBeacon('/api/metrics', JSON.stringify({
type,
data,
metadata: {
url: window.location.href,
timestamp: Date.now(),
sessionId: this.sessionId
}
}));
}
}
}A long task blocks the main thread for at least 50 ms, and sendBeacon works even while the tab is closing.
Library-specific optimization
Lodash optimization
Here tree shaking comes back: the automatic removal of unused code (dead code) from the final bundle. It works on ES modules, because import and export are static, unlike require in CommonJS. The "sideEffects": false field in package.json tells the bundler that the package modules have no side effects, so it can skip the unused ones. Classic Lodash is CommonJS:
# Build a modular ES-module version of Lodash (this is how lodash-es is generated)
npx lodash-cli modularize exports=es
# Babel plugin for automatic optimization
npm install --save-dev babel-plugin-lodashThe second part is a Babel plugin that turns an import of the whole library into imports of single functions:
// babel.config.js
module.exports = {
plugins: [
'lodash' // Automatically converts imports to cherry-picked
]
};
// Before optimization (70KB)
import _ from 'lodash';
// After optimization (2KB)
import debounce from 'lodash/debounce';
import throttle from 'lodash/throttle';Today it is simpler to reach for lodash-es. For the same reason, the Module pattern with an IIFE, although it hides private variables, cannot be trimmed, because it is a single object.
Date library optimization
Moment.js does not support tree shaking, and its authors themselves recommend newer alternatives:
// Date library size comparison (approximate and version-dependent; check current numbers e.g. on bundlephobia)
const dateLibraryComparison = {
'moment': {
size: '230KB',
gzipped: '67KB',
treeshaking: false
},
'date-fns': {
size: '78KB',
gzipped: '13KB',
treeshaking: true
},
'dayjs': {
size: '9KB',
gzipped: '3KB',
treeshaking: true
},
'luxon': {
size: '67KB',
gzipped: '19KB',
treeshaking: true
}
};
// Migration guide from Moment.js to date-fns
const migrationExamples = {
before: `
import moment from 'moment';
const formatted = moment().format('DD/MM/YYYY');
const isAfter = moment(date1).isAfter(date2);
`,
after: `
import { format, isAfter } from 'date-fns';
import { pl } from 'date-fns/locale';
const formatted = format(new Date(), 'dd/MM/yyyy', { locale: pl });
const isAfterResult = isAfter(date1, date2);
`
};The sizes are approximate. Watch the tokens: date-fns uses dd and yyyy, while Moment uses DD and YYYY.
CSS framework optimization
PurgeCSS scans the source files and removes the CSS selectors it did not find in them:
// PurgeCSS for removing unused styles
const purgecss = require('@fullhuman/postcss-purgecss');
module.exports = {
plugins: [
purgecss({
content: [
'./src/**/*.html',
'./src/**/*.js',
'./src/**/*.tsx'
],
safelist: [
/^tooltip-/,
/^modal-/,
/^dropdown-/
],
defaultExtractor: content => content.match(/[\w-/:]+(?<!:)/g) || []
})
]
};
// Example size reductions (illustrative values, they depend on the project)
const cssOptimizationResults = {
bootstrap: {
before: '150KB',
after: '23KB',
reduction: '85%'
},
tailwind: {
before: '3.2MB',
after: '12KB',
reduction: '99.6%'
},
materialUI: {
before: '890KB',
after: '145KB',
reduction: '84%'
}
};safelist protects classes that JavaScript adds dynamically.
Advanced webpack optimization
Custom webpack plugins
A custom plugin is a class with an apply method that hooks into the compiler:
// Plugin for bundle analysis and optimization
class BundleOptimizationPlugin {
constructor(options = {}) {
this.options = {
reportPath: 'bundle-optimization-report.json',
thresholds: {
maxChunkSize: 250000,
maxModuleSize: 50000
},
...options
};
}
apply(compiler) {
compiler.hooks.emit.tapAsync('BundleOptimizationPlugin', (compilation, callback) => {
const report = this.generateOptimizationReport(compilation);
// Save report
compilation.assets[this.options.reportPath] = {
source: () => JSON.stringify(report, null, 2),
size: () => JSON.stringify(report, null, 2).length
};
// Log warnings
this.logWarnings(compilation, report);
callback();
});
}
generateOptimizationReport(compilation) {
const chunks = Array.from(compilation.chunks);
const modules = Array.from(compilation.modules);
return {
timestamp: new Date().toISOString(),
summary: {
totalChunks: chunks.length,
totalModules: modules.length,
totalSize: this.calculateTotalSize(chunks)
},
chunks: chunks.map(chunk => ({
id: chunk.id,
name: chunk.name,
size: chunk.size,
modules: chunk.getModules().length,
parents: Array.from(chunk.groupsIterable, g => g.getParents()),
children: Array.from(chunk.groupsIterable, g => g.getChildren())
})),
optimizationOpportunities: this.findOptimizationOpportunities(chunks, modules),
recommendations: this.generateRecommendations(chunks, modules)
};
}
findOptimizationOpportunities(chunks, modules) {
const opportunities = [];
// Find large modules
const largeModules = modules.filter(module =>
module.size() > this.options.thresholds.maxModuleSize
);
if (largeModules.length > 0) {
opportunities.push({
type: 'LARGE_MODULES',
modules: largeModules.map(m => ({
identifier: m.identifier(),
size: m.size(),
reasons: m.reasons.map(r => r.module?.identifier())
}))
});
}
// Find duplicates
const moduleDuplicates = this.findModuleDuplicates(modules);
if (moduleDuplicates.length > 0) {
opportunities.push({
type: 'MODULE_DUPLICATES',
duplicates: moduleDuplicates
});
}
return opportunities;
}
}
// Plugin usage
module.exports = {
plugins: [
new BundleOptimizationPlugin({
thresholds: {
maxChunkSize: 200000,
maxModuleSize: 30000
}
})
]
};This is a sketch in the webpack 4 API, and you write the helper methods (calculateTotalSize, findModuleDuplicates, generateRecommendations, logWarnings) yourself. In webpack 5 you add assets in the processAssets hook with compilation.emitAsset, get a chunk's size from compilation.chunkGraph.getChunkSize(chunk), and use compilation.moduleGraph.getIncomingConnections(module) instead of the removed module.reasons.
Runtime chunk optimization
The runtime is the webpack code that loads chunks, and once extracted it does not invalidate the application cache. Next to it, JS and CSS minification:
// Runtime chunk optimization
const TerserPlugin = require('terser-webpack-plugin');
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin');
module.exports = {
optimization: {
runtimeChunk: {
name: entrypoint => `runtime-${entrypoint.name}`
},
// Minimizer configuration
minimizer: [
new TerserPlugin({
parallel: true,
terserOptions: {
parse: {
ecma: 2020
},
compress: {
ecma: 2020,
comparisons: false,
inline: 2,
drop_console: process.env.NODE_ENV === 'production',
drop_debugger: process.env.NODE_ENV === 'production',
pure_funcs: ['console.log', 'console.info', 'console.debug']
},
mangle: {
safari10: true
},
output: {
ecma: 2020,
comments: false,
ascii_only: true
}
}
}),
new CssMinimizerPlugin({
parallel: true,
minimizerOptions: {
preset: [
'default',
{
discardComments: { removeAll: true },
normalizeWhitespace: true,
colormin: true,
convertValues: true,
discardDuplicates: true,
discardEmpty: true,
mergeRules: true,
minifyFontValues: true,
minifyGradients: true,
minifyParams: true,
minifySelectors: true,
normalizeCharset: true,
normalizeDisplayValues: true,
normalizePositions: true,
normalizeRepeatStyle: true,
normalizeString: true,
normalizeTimingFunctions: true,
normalizeUnicode: true,
normalizeUrl: true,
orderedValues: true,
reduceIdents: true,
reduceInitial: true,
reduceTransforms: true,
svgo: true,
uniqueSelectors: true
}
]
}
})
]
}
};drop_console works only in production, and pure_funcs lists functions whose calls can be removed.
Bundle tests
Automated bundle testing
It is easy to break an optimization with a single import, so tests for size, duplicates and tree shaking guard it:
// Test suite for bundle optimization
const bundleTests = {
// Bundle size test
async testBundleSize() {
const bundleStats = await getBundleStats();
const maxSize = 500000; // 500KB
expect(bundleStats.totalSize).toBeLessThan(maxSize);
expect(bundleStats.mainChunk).toBeLessThan(200000);
expect(bundleStats.vendorChunk).toBeLessThan(300000);
},
// Duplicate test
async testNoDuplicateModules() {
const bundleAnalysis = await analyzeBundleContent();
const duplicates = bundleAnalysis.duplicatedModules;
expect(duplicates).toHaveLength(0);
},
// Tree shaking effectiveness test
async testTreeShakingEffectiveness() {
const unusedExports = await findUnusedExports();
const deadCode = await findDeadCode();
expect(unusedExports.length).toBeLessThan(5);
expect(deadCode.totalSize).toBeLessThan(10000);
},
// Cache effectiveness test
async testCacheability() {
const chunks = await getChunkManifest();
chunks.forEach(chunk => {
if (chunk.type === 'vendor') {
expect(chunk.hash).toMatch(/^[a-f0-9]{8}$/);
expect(chunk.cacheable).toBe(true);
}
});
}
};
// CI/CD integration
describe('Bundle Optimization Tests', () => {
test('Bundle size within limits', bundleTests.testBundleSize);
test('No duplicate modules', bundleTests.testNoDuplicateModules);
test('Tree shaking effective', bundleTests.testTreeShakingEffectiveness);
test('Chunks properly cacheable', bundleTests.testCacheability);
});You write the helper functions, such as getBundleStats, yourself, based on stats.json.
Performance regression detection
The regression detector compares the current metrics with a saved baseline:
// System for detecting performance regressions
class PerformanceRegressionDetector {
constructor() {
this.baselineMetrics = null;
this.threshold = 0.1; // 10% increase = regression
}
async setBaseline() {
this.baselineMetrics = await this.measureCurrentMetrics();
await this.saveBaseline(this.baselineMetrics);
}
async detectRegressions() {
const currentMetrics = await this.measureCurrentMetrics();
const regressions = [];
if (!this.baselineMetrics) {
this.baselineMetrics = await this.loadBaseline();
}
// Check bundle sizes
const sizeRegression = this.detectSizeRegression(
this.baselineMetrics.bundleSize,
currentMetrics.bundleSize
);
if (sizeRegression) {
regressions.push(sizeRegression);
}
// Check load times
const loadTimeRegression = this.detectLoadTimeRegression(
this.baselineMetrics.loadTime,
currentMetrics.loadTime
);
if (loadTimeRegression) {
regressions.push(loadTimeRegression);
}
return regressions;
}
detectSizeRegression(baseline, current) {
const increase = (current - baseline) / baseline;
if (increase > this.threshold) {
return {
type: 'SIZE_REGRESSION',
baseline: baseline,
current: current,
increase: `${(increase * 100).toFixed(1)}%`,
severity: increase > 0.25 ? 'HIGH' : 'MEDIUM'
};
}
return null;
}
async generateRegressionReport(regressions) {
return {
timestamp: new Date().toISOString(),
regressions: regressions,
recommendations: await this.generateRecommendations(regressions),
actionItems: this.generateActionItems(regressions)
};
}
}An increase above 10% counts as a regression, and above 25% as a high-priority regression.
Production deployment strategies
You can release a new bundle gradually and compare variants on real traffic:
// Progressive deployment strategy for bundles
class ProgressiveBundleDeployment {
constructor() {
this.deploymentStages = [
{ name: 'canary', percentage: 5 },
{ name: 'blue-green', percentage: 50 },
{ name: 'full', percentage: 100 }
];
}
async deployNewBundle(bundleVersion) {
for (const stage of this.deploymentStages) {
console.log(`Deploying to ${stage.name} (${stage.percentage}% traffic)`);
await this.deployToStage(bundleVersion, stage);
const metrics = await this.monitorStageMetrics(stage, 300000); // 5 min
if (!this.validateStageSuccess(metrics)) {
await this.rollbackStage(stage);
throw new Error(`Deployment failed at ${stage.name} stage`);
}
console.log(`Stage ${stage.name} successful`);
}
}
async monitorStageMetrics(stage, duration) {
const startTime = Date.now();
const metrics = {
errorRate: [],
loadTimes: [],
bundleErrors: []
};
while (Date.now() - startTime < duration) {
const sample = await this.collectMetricsSample(stage);
metrics.errorRate.push(sample.errorRate);
metrics.loadTimes.push(sample.avgLoadTime);
metrics.bundleErrors.push(sample.bundleErrors);
await new Promise(resolve => setTimeout(resolve, 30000)); // 30s intervals
}
return metrics;
}
validateStageSuccess(metrics) {
const avgErrorRate = metrics.errorRate.reduce((a, b) => a + b) / metrics.errorRate.length;
const avgLoadTime = metrics.loadTimes.reduce((a, b) => a + b) / metrics.loadTimes.length;
const totalBundleErrors = metrics.bundleErrors.reduce((a, b) => a + b);
return avgErrorRate < 0.01 && // < 1% error rate
avgLoadTime < 3000 && // < 3s load time
totalBundleErrors < 5; // < 5 bundle errors
}
}
// A/B testing different bundle optimization strategies
class BundleOptimizationABTest {
constructor() {
this.variants = {
control: {
strategy: 'current',
splitChunks: 'default',
compression: 'gzip'
},
optimized: {
strategy: 'aggressive_splitting',
splitChunks: 'custom',
compression: 'brotli'
},
experimental: {
strategy: 'module_federation',
splitChunks: 'micro_chunks',
compression: 'zstd'
}
};
}
async runABTest(duration = 7 * 24 * 60 * 60 * 1000) { // 7 days
const testId = this.generateTestId();
// Start test
await this.startTest(testId);
// Monitor metrics
const results = await this.monitorTest(testId, duration);
// Analyze results
const analysis = await this.analyzeResults(results);
// Select winner
const winner = this.selectWinner(analysis);
return {
testId,
duration,
results,
analysis,
winner,
recommendation: this.generateRecommendation(analysis, winner)
};
}
async monitorTest(testId, duration) {
const results = {
control: { metrics: [], samples: 0 },
optimized: { metrics: [], samples: 0 },
experimental: { metrics: [], samples: 0 }
};
const startTime = Date.now();
while (Date.now() - startTime < duration) {
for (const variant of Object.keys(this.variants)) {
const metrics = await this.collectVariantMetrics(variant);
results[variant].metrics.push(metrics);
results[variant].samples++;
}
await new Promise(resolve => setTimeout(resolve, 3600000)); // 1 hour
}
return results;
}
selectWinner(analysis) {
const scores = {};
for (const variant of Object.keys(analysis)) {
const data = analysis[variant];
scores[variant] = (
(1 / data.avgLoadTime) * 0.4 + // 40% weight
(1 / data.avgBundleSize) * 0.3 + // 30% weight
data.conversionRate * 0.2 + // 20% weight
(1 - data.errorRate) * 0.1 // 10% weight
);
}
return Object.keys(scores).reduce((a, b) =>
scores[a] > scores[b] ? a : b
);
}
}The blue-green stage is a simplification: classic blue-green switches all traffic at once, while gradually increasing the traffic share is a canary release.
Summary and checklist
Finally, a checklist and a hypothetical return on investment calculation:
const bundleOptimizationChecklist = {
analysis: [
'Webpack Bundle Analyzer setup',
'Source map analysis',
'Performance budget configured',
'CI/CD bundle size monitoring',
'Duplicate detection'
],
codeOptimization: [
'Tree shaking enabled',
'Dead code elimination',
'Unused dependencies removed',
'Code splitting implemented',
'Lazy loading configured'
],
bundleStrategy: [
'Chunk splitting optimized',
'Vendor chunks separated',
'Runtime chunk extracted',
'Common chunks identified',
'Dynamic imports utilized'
],
compression: [
'Gzip/Brotli enabled',
'Minification configured',
'CSS optimization',
'Image optimization',
'Font optimization'
],
caching: [
'Long-term caching setup',
'Content-based hashing',
'Cache invalidation strategy',
'Service worker implemented',
'CDN optimization'
],
monitoring: [
'Real user monitoring',
'Performance metrics tracking',
'Regression detection',
'A/B testing capability',
'Alert system configured'
]
};
// Hypothetical ROI (illustrative values, not research data)
const optimizationROI = {
investment: {
developmentTime: '2-3 weeks',
toolingSetup: '$5,000',
ongoingMaintenance: '$2,000/month'
},
returns: {
conversionRateIncrease: '+25-40%',
bounceRateDecrease: '-30-50%',
serverCostReduction: '-20-30%',
mobileUserRetention: '+35-60%',
seoRankingImprovement: '+15-25%'
},
businessImpact: {
revenueIncrease: '$50,000-150,000/year',
costSavings: '$20,000-40,000/year',
paybackPeriod: '2-4 months',
totalROI: '400-800%'
}
};Optimization usually pays off, but the return depends on the project, so base your decisions on your own measurements. Start with the Bundle Analyzer because a single module map usually points to the biggest culprit. In the editor below you will build the park dashboard, and in the next lesson you will learn about event-driven architecture.
Remember: every kilobyte in the bundle is cargo that visitors have to carry through the gate, so pack only what is essential.
Code for this lesson: index.js
// Park Dashboard and Interface
// Exercise: Implement a dashboard rendering system
class ParkDashboard {
constructor() {
this.widgets = [];
this.data = {};
}
// Implement the methods:
// addWidget(name, renderFn) - add a widget
// updateData(key, value) - update data
// render() - render all widgets
addWidget(name, renderFn) {
// Your code here
}
updateData(key, value) {
// Your code here
}
render() {
// Your code here
}
}
const dashboard = new ParkDashboard();
console.log("Dashboard ready for configuration");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 is tree shaking in the context of JavaScript bundling?
2. Which module format enables effective tree shaking?
These are 2 of 6 questions for this lesson. Solve the rest in the game.
Hands-on tasks in the game
- Vertical ordering
Arrange the stages of refactoring code to a design pattern:
- Code editor
The index.js file has three unit tests: functions that receive the class to check and should return true for a correct class and false for a class with a bug. Fill in the blanks: ___BLANK1___ is the comparison operator that checks that getModule returns the same object that was registered, ___BLANK2___ is the comparison operator that checks that two ids are different, and ___BLANK3___ is the number of alerts we expect when only one of two sensors exceeds its threshold. The checker runs your tests on correct ParkCore, DinosaurRegistry and SecuritySystem classes and on versions with bugs (a copy of the module instead of the original, one id for everybody, an alarm at a reading equal to the threshold).
- Vertical ordering
Arrange the user interface elements in the order in which they appear in the HTML code of the page (starting with the outer container):
- Code editor
The index.js file has a PerformanceMonitor class. Fill in the blanks: ___BLANK1___ is the method of the performance object that returns the current time in milliseconds with high precision (measure uses the same method for the end time), ___BLANK2___ is the array method that adds up all durations (it starts from 0), and ___BLANK3___ is the Math method that returns the largest duration. measure(name, fn) should return the result of fn and store the measurement { name, duration }, and getReport(name) should return { count, min, max, avg } for the measurements with this name, or null when there are none.
- Click in order
Arrange the steps for implementing lazy loading of a component in JavaScript:
- Horizontal ordering
Arrange the elements of a module export in the correct order:
- Click in order
Arrange the elements of the Observer pattern:
- Vertical ordering
Arrange the steps of Factory pattern implementation in the correct order:
- Vertical ordering
Arrange the data flow in the dinosaur management system:
- Vertical ordering
Arrange the elements of dependency injection in the correct order:
- Vertical ordering
Arrange the stages of implementing code splitting in an application:
- Vertical ordering
Arrange the stages of Observer pattern implementation in an application:
- Horizontal ordering
Arrange the elements of freezing an object:
Tasks after this lesson
- Put in orderStages of Refactoring to a Design Pattern
- QuestionTree Shaking
- QuestionTree Shaking Requirements
- Coding taskExercise: Testing Framework
- Put in orderVertical Sorting: UI Components
- Coding taskExercise: Performance Monitoring
- QuestionBundle Analysis
- Click in orderLazy Loading a Component
- Put in orderSequence: Module Export Pattern
- Click in orderSorting: Observer Pattern
- QuestionBundle Analysis Tool
- Put in orderFactory Pattern Implementation
- Put in orderVertical Sorting: Data Flow
- Put in orderSequence: Dependency Injection
- QuestionThe sideEffects Field in package.json
- Put in orderStages of Code Splitting
- Put in orderStages of Observer Pattern Implementation
- QuestionPurpose of the IIFE Module Pattern
- Put in orderObject.freeze Syntax