1. 前端工程选型决策矩阵

技术维度选型方案传统/替代方案决策依据与工程收益
组件组织范式Standalone 独立组件NgModule 模块封装消除中间层样板配置,实现细粒度组件自治与极致 Tree-shaking 剪枝
模板控制流原生块级控制流 (@if, @for, @switch)结构型指令 (*ngIf, *ngFor)编译器原生语法支持,严格类型推导,强制显式 track 优化 DOM 重排
组件通信机制Signal-based input() / output()装饰器 @Input() / @Output()细粒度响应式信号模型,只读类型安全,解耦 Zone.js 变更检测生命周期
依赖注入方式函数式 inject() 注入构造函数参数注入允许在字段声明处即时初始化,简化派生类 super() 参数传递
单元测试体系Vitest 现代测试套件Karma + Jasmine原生 ESM 解析与 Vite 极速 HMR,测试执行与冷启动速度提升 5~10 倍
变更检测模型Zoneless (无 Zone.js) 调度Zone.js 全局事件拦截依托 Signals 精确派发局部 DOM 刷新,消除不可预测的全局脏检查开销

2. Feature-First 生产级工程拓扑

大型企业级前端项目遵循按业务特性垂直切分(Feature-First)原则,保持业务域高内聚与跨层级单向依赖:

text
src/
├── app/
│   ├── features/               # 业务特性层(按垂直领域边界划分)
│   │   ├── books/              # 图书目录与管理特性
│   │   │   ├── pages/          # Smart 容器页面(协调路由与服务状态)
│   │   │   ├── components/     # 特性专属 Dumb 展示组件(纯输入输出驱动)
│   │   │   └── books.routes.ts # 特性专属子路由配置
│   │   ├── auth/               # 认证与用户特性
│   │   └── orders/             # 订单特性
│   ├── shared/                 # 跨特性通用层(纯 Dumb 组件、通用模型、管道)
│   │   ├── layout/             # 布局骨架(Header, Footer, Navigation)
│   │   └── models/             # 契约模型(严格对齐后端 DTO 接口)
│   ├── core/                   # 全局单例基础设施(HTTP 拦截器、Guard、Store)
│   │   └── services/           # 全局单例服务
│   ├── app.ts                  # 根组件(自包含 Standalone)
│   ├── app.routes.ts           # 顶层懒加载路由配置
│   └── app.config.ts           # 全局 Providers 与运行时配置

3. Smart/Dumb 响应式组件生产范式

契约模型定义 (shared/models/book.ts)

typescript
export interface Book {
  title: string;
  authorName: string;
  genre: string;
  price: number;
  published: string;
  isbn: string;
  description?: string;
  pageCount?: number;
  coverImageUrl?: string;
}

Dumb 展示组件 (book-list.ts)

typescript
import { Component, input, output } from '@angular/core';
import { CurrencyPipe } from '@angular/common';
import { MatTableModule } from '@angular/material/table';
import { MatIconModule } from '@angular/material/icon';
import { MatButtonModule } from '@angular/material/button';
import { Book } from '../../../../shared/models/book';
 
@Component({
  selector: 'book-list',
  standalone: true,
  imports: [CurrencyPipe, MatTableModule, MatIconModule, MatButtonModule],
  template: `
    <table mat-table [dataSource]="books()" class="mat-elevation-z2 full-width-table">
      <ng-container matColumnDef="title">
        <th mat-header-cell *matHeaderCellDef>书名</th>
        <td mat-cell *matCellDef="let book">{{ book.title }}</td>
      </ng-container>
 
      <ng-container matColumnDef="authorName">
        <th mat-header-cell *matHeaderCellDef>作者</th>
        <td mat-cell *matCellDef="let book">{{ book.authorName }}</td>
      </ng-container>
 
      <ng-container matColumnDef="genre">
        <th mat-header-cell *matHeaderCellDef>分类</th>
        <td mat-cell *matCellDef="let book">{{ book.genre }}</td>
      </ng-container>
 
      <ng-container matColumnDef="price">
        <th mat-header-cell *matHeaderCellDef>定价</th>
        <td mat-cell *matCellDef="let book">{{ book.price | currency:'USD':'symbol':'1.2-2' }}</td>
      </ng-container>
 
      <ng-container matColumnDef="actions">
        <th mat-header-cell *matHeaderCellDef>操作</th>
        <td mat-cell *matCellDef="let book">
          <button mat-icon-button color="primary" (click)="onSelect(book, $event)" aria-label="选择图书">
            <mat-icon>visibility</mat-icon>
          </button>
        </td>
      </ng-container>
 
      <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
      <tr mat-row *matRowDef="let row; columns: displayedColumns;" class="clickable-row"></tr>
    </table>
  `,
  styles: [`
    .full-width-table { width: 100%; }
    .clickable-row:hover { background-color: rgba(0, 0, 0, 0.04); cursor: pointer; }
  `]
})
export class BookList {
  // 强类型 Signal-based Input 与 Output
  readonly books = input<Book[]>([]);
  readonly bookSelected = output<Book>();
 
  readonly displayedColumns: string[] = ['title', 'authorName', 'genre', 'price', 'actions'];
 
  onSelect(book: Book, event: MouseEvent): void {
    event.stopPropagation();
    this.bookSelected.emit(book);
  }
}

Smart 容器组件 (list.ts)

typescript
import { Component, signal } from '@angular/core';
import { Book } from '../../../../shared/models/book';
import { BookList } from '../../components/book-list/book-list';
 
@Component({
  selector: 'books-list-page',
  standalone: true,
  imports: [BookList],
  template: `
    <section class="page-container p-4">
      <h2 class="text-xl font-bold mb-4">图书资源总览</h2>
      <book-list
        [books]="books()"
        (bookSelected)="handleBookSelection($event)"
      />
    </section>
  `
})
export class BooksListPage {
  readonly books = signal<Book[]>([
    {
      title: 'Designing Data-Intensive Applications',
      authorName: 'Martin Kleppmann',
      genre: 'Distributed Systems',
      price: 49.99,
      published: '2017-03-16',
      isbn: '978-1449373320'
    }
  ]);
 
  handleBookSelection(book: Book): void {
    console.log('[Audit] 用户选中图书:', book.isbn, book.title);
  }
}

4. Vitest 与 Zoneless 自动化测试范式

在 Zoneless 架构下,变更检测基于微任务调度,测试通过 await fixture.whenStable() 确保状态稳定收敛:

typescript
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { BookList } from './book-list';
import { Book } from '../../../../shared/models/book';
import { describe, it, expect, beforeEach, vi } from 'vitest';
 
describe('BookList Component (Dumb)', () => {
  let component: BookList;
  let fixture: ComponentFixture<BookList>;
 
  const mockBooks: Book[] = [
    {
      title: 'Clean Architecture',
      authorName: 'Robert C. Martin',
      genre: 'Architecture',
      price: 34.99,
      published: '2017-09-20',
      isbn: '978-0134494166'
    }
  ];
 
  beforeEach(async () => {
    await TestBed.configureTestingModule({
      imports: [BookList]
    }).compileComponents();
 
    fixture = TestBed.createComponent(BookList);
    component = fixture.componentInstance;
  });
 
  it('应该成功实例化组件并在无数据时稳定渲染', async () => {
    await fixture.whenStable();
    expect(component).toBeTruthy();
  });
 
  it('设置 Signal Input 后能够驱动视图刷新并同步信号状态', async () => {
    // 使用 componentRef.setInput 设置响应式输入信号
    fixture.componentRef.setInput('books', mockBooks);
    await fixture.whenStable();
 
    expect(component.books()).toEqual(mockBooks);
    expect(component.books().length).toBe(1);
  });
 
  it('触发操作按钮点击应通过 Output 信号正确发射目标对象', async () => {
    const selectSpy = vi.fn();
    component.bookSelected.subscribe(selectSpy);
 
    fixture.componentRef.setInput('books', mockBooks);
    await fixture.whenStable();
 
    component.onSelect(mockBooks[0], new MouseEvent('click'));
    await fixture.whenStable();
 
    expect(selectSpy).toHaveBeenCalledWith(mockBooks[0]);
  });
});

5. 前端架构避坑清单 (Do's & Don'ts)

错误实践 (Don't)正确实践 (Do)
创建集中式的 SharedModule 或 MaterialModule 全量打包所有组件。在每个独立组件中仅按需引入模板直接消费的 Material 模块或组件,保障 Tree-shaking 最小产物。
在原生 @for 循环中使用易变的 $index 作为强制 track 标识。强制使用稳定的领域唯一主键(如 track book.isbn),避免列表变更时的全量 DOM 销毁重建。
在 Zoneless 测试中依旧频繁手动调用 fixture.detectChanges() 轮询脏检查。使用 await fixture.whenStable() 挂起断言,等待 Signals 响应式调度器微任务自然收敛。
在 Dumb 展示组件内部通过注入服务直接发起 HTTP 请求或改变全局 Store。严格保持展示组件无状态:仅通过 input() 获取展示数据,通过 output() 发射交互事件由 Smart 容器处理。
使用传统属性装饰器 @Input()、@Output() 编写混杂类型。全面迁移至类型安全、基于 Signals 的 input()、output() 现代原生 API。