TypeScript Import vs Component Import

基本概念

Angular 有兩種主要的 import 方式:

  1. TypeScript import(檔案頂部的 import 語句)

  2. Component imports(@Component 裝飾器中的 imports 陣列)

使用規則

1. TypeScript Import

  • 用於在組件類(class)中使用的功能

  • 在檔案頂部使用 import 語句

  • 包含所有在程式邏輯中使用的類別、介面、函數等

2. Component Import

  • 用於在模板(template)中使用的功能

  • 在 @Component 裝飾器的 imports 陣列中宣告

  • 包含所有在 HTML 模板中使用的指令、管道、組件等

實際範例

// 1. TypeScript imports
import { Component } from '@angular/core';                // 用於裝飾器
import { FormGroup, FormControl, Validators } from '@angular/forms';  // 用於表單邏輯
import { HttpClient } from '@angular/common/http';        // 用於 HTTP 請求
import { map } from 'rxjs/operators';                    // 用於 RxJS 操作

// 2. Component imports
@Component({
  selector: 'app-root',
  imports: [
    ReactiveFormsModule,    // 因為模板中使用 formGroup 指令
    CommonModule,           // 因為模板中使用 *ngIf, *ngFor
    UserComponent          // 因為模板中使用 <app-user>
  ],
  template: `
    <form [formGroup]="form">              <!-- 需要 ReactiveFormsModule -->
      <input formControlName="name">
      <div *ngIf="form.valid">            <!-- 需要 CommonModule -->
        <app-user></app-user>             <!-- 需要 UserComponent -->
      </div>
    </form>
  `
})
export class AppComponent {
  // 在類中使用 TypeScript imported 的功能
  form = new FormGroup({
    name: new FormControl('', [
      Validators.required,  // Validators 只在類中使用
      Validators.minLength(4)
    ])
  });

  constructor(private http: HttpClient) {  // HttpClient 只在類中使用
    this.http.get('/api')
      .pipe(map(res => res))              // map 只在類中使用
      .subscribe();
  }
}

常見場景分類

只需要 TypeScript Import

  • FormControl, FormGroup, Validators

  • HttpClient 和相關服務

  • RxJS 運算符和工具

  • 介面(Interface)和類型定義

  • 工具函數和類別

需要 Component Import

  • 指令(如 *ngIf, *ngFor)

  • 管道(如 | date, | currency)

  • 其他組件(用在模板中的組件)

  • 表單指令(如 formGroup, formControl)

  • 路由指令(如 routerLink)

注意事項

  1. 驗證器(Validators)特例:

// Validators 只需要 TypeScript import
import { Validators } from '@angular/forms';

// 雖然在模板中可以看到驗證結果
<button [disabled]="!form.valid">Submit</button>
// 但這裡使用的是 FormGroup 的 valid 屬性,不是直接使用 Validators
  1. 服務(Services)特例:

// 服務只需要 TypeScript import
import { UserService } from './user.service';

// 即使服務的結果顯示在模板中
<div>{{ userService.getData() }}</div>

判斷方法

要判斷是否需要在 Component imports 中引入,可以問自己:

  1. 這個功能是否直接在 HTML 模板中使用?

  2. 是否使用了特定的模板語法(如 *ngIf, [(ngModel)])?

  3. 是否在模板中使用了自定義組件標籤?

  • 如果答案是「是」→ 需要在 Component imports 中引入

  • 如果答案是「否」→ 只需要 TypeScript import

最佳實踐

  1. 保持邏輯清晰:

    • TypeScript imports 用於程式邏輯

    • Component imports 用於模板功能

  2. 避免不必要的 imports:

    • 不要在 Component imports 中引入未在模板中使用的功能

    • 不要重複引入已經被其他模組包含的功能

  3. 考慮性能:

    • 只引入需要的功能

    • 使用適當的模組分割

Last updated