Angular course · Module 12: Security and Performance
Profiling and Diagnostics
In this lesson5
Angular DevTools
Angular DevTools is an inspector for your application:
- Component Explorer - component tree
- Profiler - change detection performance analysis
- Injection Graph - dependency injection map
# Install the extension
# Chrome Web Store: Angular DevToolsPerformance Profiling
// Enable profiling in development
import { ApplicationConfig } from '@angular/core';
export const appConfig: ApplicationConfig = {
providers: [
// In development we can enable detailed logging
]
};
// Manual measurements
@Component({...})
export class ProfiledComponent {
loadData(): void {
console.time('loadData');
// Operations...
console.timeEnd('loadData');
}
}Bundle Size Optimization
# Bundle analysis
ng build --stats-json
npx webpack-bundle-analyzer dist/browser/stats.json
# Source map explorer
npx source-map-explorer dist/browser/*.jsTree Shaking
// BAD - import entire library
import * as lodash from 'lodash';
// GOOD - import only needed functions
import { debounce } from 'lodash-es';
// BEST - use native methods or write your own
const debounce = (fn: Function, ms: number) => {
let timeoutId: ReturnType<typeof setTimeout>;
return (...args: any[]) => {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => fn(...args), ms);
};
};trackBy for @for
@Component({
template: `
@for (samurai of samuraiList(); track samurai.id) {
<app-samurai-card [samurai]="samurai" />
}
`
})
export class ListComponent {
// track samurai.id prevents re-rendering
// the entire list when only one element changes
}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. How do you reduce the bundle size in Angular?
2. What is the Profiler tab in Angular DevTools used for?
Hands-on tasks in the game
- Vertical ordering
Order the lines that measure the time of an operation using console.time (top to bottom):
- Code editor
Complete the template with deferred loading of a heavy component.
- Horizontal ordering
Arrange a tree-shaking-friendly import (only the needed function, from the left):
- Click in order
Build the @for loop header with a track function by id (click in order):