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 - Webpack runtime code
- Polyfills - Browser compatibility code
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, "aot": true, "extractLicenses": true, "buildOptimizer": true, "budgets": [ { "type": "initial", "maximumWarning": "500kb", "maximumError": "1mb" } ] } }}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', standalone: true, imports: [CommonModule] // Only import what's needed})
// ❌ Avoid importing entire modulesimport { BrowserModule } from '@angular/platform-browser';📊 Bundle Analysis
Section titled “📊 Bundle Analysis”Webpack Bundle Analyzer
Section titled “Webpack Bundle Analyzer”# Installnpm install --save-dev webpack-bundle-analyzer
# Build with statsng build --stats-json
# Analyzenpx webpack-bundle-analyzer dist/stats.jsonSource 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/**/*.js✅ 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 productionif (!environment.production) { 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! 📦