关于 angular-performance
面向 Angular 开发者的性能优化参考技能,涵盖变更检测、延迟加载、渲染实践、无 Zone 功能和包体积分析。
主要功能
- 01OnPush 变更检测
- 02延迟加载路由与视图
- 03在 @for 循环中跟踪项目
- 04无 Zone 变更检测建议
- 05分析包体积
适用场景
- 01减少不必要的组件检查
- 02按需延迟加载组件
- 03避免模板重复计算
- 04检查生产构建的包体积
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ oguzhan18/ angular-ecosystem-skills --skill angular-performance安装后在 Claude Code 中输入/angular-performance确认已加载。
包含的文件
除 SKILL.md 外,安装时一起下载的参考资料和脚本。
references/discussions/_INDEX.mdreferences/docs/_INDEX.mdreferences/issues/_INDEX.mdreferences/releases/_INDEX.md详细介绍
Angular 性能优化
版本: Angular 21(2025) 标签: 性能、优化、包体积、变更检测
API 变更
本节记录特定近期版本的 API 变更。
-
新增:无 Zone 变更检测 — 禁用 zone.js 以提升性能 来源
-
新增:可延迟视图(@defer)— 延迟加载组件代码
-
新增:基于 Signal 的响应式 — 使用 signals 代替 zone.js
-
新增:afterNextRender — 无需 zone.js,在渲染后运行代码
最佳实践
- 使用 OnPush 变更检测策略
@Component({
changeDetection: ChangeDetectionStrategy.OnPush,
// ...
})
export class MyComponent {}
- 在 @for 中使用 trackBy
@Component({
template: `
@for (item of items; track item.id) {
{{ item.name }}
}
`
})
export class MyComponent {}
- 对路由使用延迟加载
const routes: Routes = [
{
path: 'dashboard',
loadComponent: () => import('./dashboard/dashboard.component').then(m => m.DashboardComponent)
}
];
- 使用 @defer 实现延迟加载
@Component({
template: `
@defer (on viewport) {
<heavy-chart-component />
} @placeholder {
<div>Loading...</div>
}
`
})
export class MyComponent {}
- 在 @for 循环中使用 trackBy
@for (item of items; track item.id) {
<li>{{ item.name }}</li>
}
- 使用纯管道
@Pipe({
name: 'myPipe',
pure: true // Default - only runs when input changes
})
export class MyPipe implements PipeTransform {}
- 避免在模板中调用函数
// ❌ Bad
{{ calculateTotal() }}
// ✅ Good
{{ total }}
- 对图片使用 ngSrc
<img [ngSrc]="imageUrl" width="100" height="100" priority>
- 必要时手动使用 ChangeDetectionRef
constructor(private cdr: ChangeDetectorRef) {}
updateData() {
this.data = newData;
this.cdr.detectChanges();
}
- 对第三方库使用 runOutsideAngular
import { runOutsideAngular } from '@angular/core/zone';
onClick() {
runOutsideAngular(() => {
this第三方Lib.doSomething();
});
}
- 使用 provideZonelessChangeDetection
export const appConfig: ApplicationConfig = {
providers: [
provideZonelessChangeDetection()
]
};
- 使用 afterNextRender 进行初始化
constructor() {
afterNextRender(() => {
// Runs after rendering, outside zone
});
}
- 优化包体积
# Analyze bundle
ng build --stats-json
npx webpack-bundle-analyzer dist/stats.json
- 使用独立组件
@Component({
standalone: true,
imports: [CommonModule],
// ...
})
export class MyComponent {}
评论
支持 Markdown