Bundle Optimization 📦
Bundle optimization reduces application size, improves load times, and enhances user experience. Master techniques to create lean, fast-loading Angular applications.
🎯 Bundle Size Fundamentals
Section titled “🎯 Bundle Size Fundamentals”Key Concepts:
- Initial Bundle - Code loaded on first page load
- Lazy Bundles - Code loaded on demand
- Vendor Bundle - Third-party libraries
- Runtime Bundle - Build tool runtime code
- Polyfills - Browser compatibility code
Note: Angular uses esbuild as the default builder since Angular 17, replacing Webpack. esbuild provides significantly faster builds with automatic tree shaking and optimizations. The concepts below still apply regardless of the build tool.
Target Sizes:
- Initial bundle: < 200KB (gzipped)
- Total JavaScript: < 500KB (gzipped)
- First Load JS: < 100KB (ideal)
🚀 Production Build Optimization
Section titled “🚀 Production Build Optimization”Build Configuration
Section titled “Build Configuration”{ "configurations": { "production": { "optimization": true, "outputHashing": "all", "sourceMap": false, "namedChunks": false, "budgets": [ { "type": "initial", "maximumWarning": "500kb", "maximumError": "1mb" } ] } }}Note: With the esbuild builder (default since Angular 17), options like
aotandbuildOptimizerare no longer needed — AOT compilation and build optimization are always enabled automatically.
Tree Shaking
Section titled “Tree Shaking”// ✅ Import only what you needimport { map, filter } from 'rxjs/operators';
// ❌ Avoid importing everythingimport * as rxjs from 'rxjs';
// ✅ Specific lodash importsimport debounce from 'lodash-es/debounce';
// ❌ Avoid full lodashimport _ from 'lodash';🎨 Optimization Techniques
Section titled “🎨 Optimization Techniques”1. Lazy Loading
Section titled “1. Lazy Loading”export const routes: Routes = [ { path: '', loadComponent: () => import('./home/home.component') .then(m => m.HomeComponent) }, { path: 'admin', loadChildren: () => import('./admin/admin.routes') .then(m => m.ADMIN_ROUTES) }];2. Code Splitting
Section titled “2. Code Splitting”// Dynamic imports for heavy librariesasync loadChart() { const { Chart } = await import('chart.js'); // Use Chart.js only when needed}
async loadEditor() { const { Editor } = await import('tinymce'); // Load editor on demand}3. Remove Unused Code
Section titled “3. Remove Unused Code”// ✅ Use standalone components@Component({ selector: 'app-user', imports: [CommonModule] // Only import what's needed})
// ❌ Avoid importing entire modulesimport { BrowserModule } from '@angular/platform-browser';📊 Bundle Analysis
Section titled “📊 Bundle Analysis”Source Map Explorer
Section titled “Source Map Explorer”# Installnpm install --save-dev source-map-explorer
# Build with source mapsng build --source-map
# Analyzenpx source-map-explorer dist/**/*.jsBundle Size Inspection
Section titled “Bundle Size Inspection”# View bundle stats directlyng build --stats-json
# Use esbuild-visualizer or source-map-explorer to inspectnpx esbuild-visualizer --metadata dist/stats.json --open✅ Best Practices
Section titled “✅ Best Practices”1. Lazy Load Routes
Section titled “1. Lazy Load Routes”// ✅ Lazy load feature modules{ path: 'dashboard', loadChildren: () => import('./dashboard/routes')}
// ❌ Avoid eager loading everythingimport { DashboardModule } from './dashboard';2. Use Production Mode
Section titled “2. Use Production Mode”# ✅ Always build for productionng build --configuration production
# ❌ Avoid development buildsng build3. Optimize Images
Section titled “3. Optimize Images”// ✅ Use NgOptimizedImage<img ngSrc="/hero.jpg" width="1200" height="600" priority>
// ✅ Use WebP format<img ngSrc="/hero.webp" width="1200" height="600">4. Remove Console Logs
Section titled “4. Remove Console Logs”// ✅ Remove in production using isDevMode()import { isDevMode } from '@angular/core';
if (isDevMode()) { console.log('Debug info');}
// Or use build optimizer to strip them5. Use Differential Loading
Section titled “5. Use Differential Loading”{ "compilerOptions": { "target": "ES2022" // Modern browsers }}🎯 Optimization Checklist
Section titled “🎯 Optimization Checklist”- Enable production mode
- Implement lazy loading
- Use tree shaking
- Optimize images
- Remove unused dependencies
- Enable compression (gzip/brotli)
- Set bundle budgets
- Analyze bundle size
- Use CDN for assets
- Enable caching headers
🎓 Learning Checklist
Section titled “🎓 Learning Checklist”- Understand bundle composition
- Configure production builds
- Implement lazy loading
- Use bundle analyzers
- Optimize third-party libraries
- Set and monitor budgets
- Enable compression
- Optimize assets
🚀 Next Steps
Section titled “🚀 Next Steps”- Performance Optimization - Optimize runtime performance
- Memory Management - Prevent memory leaks
- Micro Frontends - Scale your architecture
Pro Tip: Monitor bundle sizes continuously! Set strict budgets in angular.json and use bundle analyzers regularly. Every kilobyte counts for user experience! 📦