Skip to main content

使用 Transloco 實現 Angular i18n:設定與翻譯指南

從安裝到生產:設定 Transloco、使用 ICU 語法處理複數、新增智能語言回退,並利用 AI 自動翻譯。

1

安裝 Transloco

Transloco 是 Angular 最流行的第三方 i18n 庫,提供執行階段譯文載入、ICU 訊息格式支援、延遲載入的作用域,以及同時支援結構指令和管道的簡潔範本 API。

為什麼選擇 Transloco 而不是 Angular 內置 i18n?Angular 內置方案要求每種語言單獨構建,且不支援執行階段切換語言。Transloco 在執行階段載入譯文,因此只需發佈一個構建即可隨時切換語言。
Terminal
npm install @jsverse/transloco
2

設定 Transloco

在應用程式設定中註冊 Transloco。你需要提供可用語言、設定預設語言並設定譯文載入器。Transloco 同時支援獨立元件(Angular 14+)和 NgModule 模式。

獨立元件(推薦)

app.config.ts
// app.config.ts
import { ApplicationConfig } from '@angular/core';
import { provideHttpClient } from '@angular/common/http';
import {
  provideTransloco,
  TranslocoHttpLoader,
} from '@jsverse/transloco';

export const appConfig: ApplicationConfig = {
  providers: [
    provideHttpClient(),
    provideTransloco({
      config: {
        availableLangs: ['en', 'de', 'ja', 'es', 'fr'],
        defaultLang: 'en',
        fallbackLang: 'en',
        reRenderOnLangChange: true,
        prodMode: true,
      },
      loader: TranslocoHttpLoader,
    }),
  ],
};

NgModule 模式

app.module.ts
// app.module.ts
import { NgModule } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import {
  TranslocoModule,
  TRANSLOCO_LOADER,
  TranslocoHttpLoader,
  provideTransloco,
} from '@jsverse/transloco';

@NgModule({
  imports: [TranslocoModule],
  providers: [
    provideTransloco({
      config: {
        availableLangs: ['en', 'de', 'ja', 'es', 'fr'],
        defaultLang: 'en',
        fallbackLang: 'en',
        reRenderOnLangChange: true,
        prodMode: true,
      },
      loader: TranslocoHttpLoader,
    }),
  ],
})
export class AppModule {}
如果顯示 "nav.home" 等原始鍵而不是 "Home",最常見的原因是 TranslocoHttpLoader 找不到 JSON 檔案。請確認翻譯檔案位於 src/assets/i18n/,並且 angular.json 的 assets 陣列包含該路徑。

建立翻譯檔案

在 src/assets/i18n/ 中為每種語言建立一個 JSON 檔案。使用嵌套鍵按功能組織字串。Transloco 使用 ICU 訊息格式處理複數和變數。

assets/i18n/*.json
// assets/i18n/en.json
{
  "nav": {
    "home": "Home",
    "about": "About",
    "settings": "Settings"
  },
  "greeting": "Hello, {{ name }}!",
  "cart": {
    "itemCount": "{count, plural, one {# item} other {# items}}"
  }
}

// assets/i18n/de.json
{
  "nav": {
    "home": "Startseite",
    "about": "Uber uns",
    "settings": "Einstellungen"
  },
  "greeting": "Hallo, {{ name }}!",
  "cart": {
    "itemCount": "{count, plural, one {# Artikel} other {# Artikel}}"
  }
}
3

在範本和服務中使用譯文

Transloco 提供三種範本翻譯方式:結構指令(*transloco)、管道(| transloco),以及供 TypeScript 程式碼使用的服務(TranslocoService)。大多數場景推薦結構指令,因為它只建立一個訂閱,並將 translate 函數提供給整個範本塊。

範本翻譯

component.html
<!-- Using the transloco directive (recommended) -->
<ng-container *transloco="let t">
  <h1>{{ t('greeting', { name: userName }) }}</h1>
  <nav>
    <a routerLink="/">{{ t('nav.home') }}</a>
    <a routerLink="/about">{{ t('nav.about') }}</a>
  </nav>
</ng-container>

<!-- Using the transloco pipe -->
<h1>{{ 'greeting' | transloco:{ name: userName } }}</h1>

<!-- Using the structural directive with read -->
<ng-container *transloco="let t; read: 'nav'">
  <a routerLink="/">{{ t('home') }}</a>
  <a routerLink="/about">{{ t('about') }}</a>
</ng-container>
在結構指令中使用 read 參數,將譯文作用域限定到嵌套鍵。這樣無需在每次 t() 呼叫中重復前綴,範本也更簡潔。

服務翻譯(TypeScript)

notification.component.ts
import { Component, inject } from '@angular/core';
import { TranslocoService } from '@jsverse/transloco';

@Component({
  selector: 'app-notification',
  template: '<span>{{ message }}</span>',
})
export class NotificationComponent {
  private translocoService = inject(TranslocoService);
  message = '';

  showSuccess() {
    // Translate in TypeScript
    this.message = this.translocoService.translate('notifications.saved');
  }

  switchLanguage(lang: string) {
    this.translocoService.setActiveLang(lang);
  }
}
transloco 管道每使用一次就會建立一個新訂閱。範本包含大量翻譯字串時,應優先使用 *transloco 結構指令,它只為整個塊建立一個訂閱。
4

使用 ICU 訊息格式處理複數

Transloco 使用 ICU 訊息格式處理複數和 select 表達式。ICU 可自動處理複雜複數規則,包括阿拉伯語 6 種形式、俄語 3 種、日語 1 種,全部來自單個訊息字串。請在翻譯檔案中定義複數規則,Transloco 會在執行階段選擇正確形式。

ICU plural syntax
// assets/i18n/en.json
{
  "cart": {
    "itemCount": "{count, plural, one {# item} other {# items}}",
    "emptyMessage": "Your cart is empty"
  },
  "notifications": {
    "unread": "{count, plural, =0 {No new notifications} one {# new notification} other {# new notifications}}"
  }
}

// assets/i18n/ar.json — Arabic has 6 plural forms
{
  "cart": {
    "itemCount": "{count, plural, zero {لا عناصر} one {عنصر واحد} two {عنصران} few {# عناصر} many {# عنصرًا} other {# عنصر}}"
  }
}

// Template usage:
// <span>{{ t('cart.itemCount', { count: cartItems.length }) }}</span>
切勿在元件中實現自訂複數邏輯。各語言的複數規則差異極大,而 ICU 規範已經能夠處理。讓 Transloco 和 ICU 完成這項工作,你只需在翻譯檔案中定義正確的複數形式。

使用 angular-locale-chain 實現智能語言回退

預設情況下,缺少翻譯鍵時 Transloco 會回退到預設語言。pt-BR 用戶會看到英語,而不是完全可用的 pt-PT 譯文。angular-locale-chain 會先深度合併可設定回退鏈中的譯文,再交給 Transloco,確保每個鍵都有內容,不留缺口或缺失譯文。

Terminal
npm install angular-locale-chain
app.config.ts (with locale chain)
// app.config.ts — with angular-locale-chain
import { ApplicationConfig } from '@angular/core';
import { provideHttpClient } from '@angular/common/http';
import {
  provideTransloco,
  TranslocoHttpLoader,
  TRANSLOCO_LOADER,
  TRANSLOCO_FALLBACK_STRATEGY,
} from '@jsverse/transloco';
import {
  LocaleChainLoader,
  LocaleChainFallbackStrategy,
} from 'angular-locale-chain';

export const appConfig: ApplicationConfig = {
  providers: [
    provideHttpClient(),
    provideTransloco({
      config: {
        availableLangs: ['en', 'fr', 'fr-CA', 'pt', 'pt-BR', 'de', 'de-AT'],
        defaultLang: 'en',
        fallbackLang: 'en',
        reRenderOnLangChange: true,
        prodMode: true,
      },
    }),
    {
      provide: TRANSLOCO_LOADER,
      useFactory: () => {
        const inner = new TranslocoHttpLoader();
        return new LocaleChainLoader(inner, {
          defaultLocale: 'en',
        });
      },
    },
    {
      provide: TRANSLOCO_FALLBACK_STRATEGY,
      useFactory: () => new LocaleChainFallbackStrategy(),
    },
  ],
};
angular-locale-chain 是一個開源庫,用於解決 Transloco bug #574,即翻譯檔案部分完成時缺少逐鍵回退的問題。

推薦的檔案結構

Project Structure
my-angular-app/
├── src/
│   ├── assets/
│   │   └── i18n/
│   │       ├── en.json           # Source language
│   │       ├── de.json           # German
│   │       ├── ja.json           # Japanese
│   │       ├── es.json           # Spanish
│   │       └── fr.json           # French
│   ├── app/
│   │   ├── app.config.ts         # Transloco provider config
│   │   ├── app.component.ts
│   │   └── components/
│   │       └── lang-switcher/
│   │           └── lang-switcher.component.ts
│   └── main.ts
├── angular.json
└── package.json

自動翻譯

完成 Transloco 設定後,使用 AI 翻譯本地化檔案。在 IDE 中讓 AI 助手翻譯源 JSON 檔案,或在 CI/CD 管線中使用 i18n Agent CLI 實現全自動本地化。

Terminal
# In your IDE, ask your AI assistant:
> Translate src/assets/i18n/en.json to German, Japanese, and Spanish

✓ de.json created (1.2s)
✓ ja.json created (1.5s)
✓ es.json created (1.1s)

# Or use the CLI in CI/CD:
npx i18n-agent translate src/assets/i18n/en.json --lang de,ja,es
採用增量翻譯:向來源檔案新增新鍵時,只翻譯差異,不要重新產生所有檔案。這樣既保留人工審核的譯文,也避免不必要的變動。

自動保證翻譯質素

使用 i18n-validate 在發佈前發現缺失鍵和損壞的預留位置。真實譯文完成前,可使用 i18n-pseudo 產生偽譯文來測試 UI。

常見問題

譯文顯示原始鍵

TranslocoHttpLoader 找不到 JSON 檔案。請檢查檔案是否位於 src/assets/i18n/、angular.json 的 assets 陣列是否包含該路徑,以及檔案名是否與 availableLangs 設定完全匹配(區分大小寫)。

無法解析作用域鍵

使用 Transloco scope 時,翻譯檔案必須位於 assets/i18n/[scope]/[lang].json,而不是根 i18n 資料夾。還要確保通過 TRANSLOCO_SCOPE 在元件的 providers 陣列中註冊 scope。

生產環境中的控制台警告

生產構建應在 Transloco 設定中設定 prodMode: true。否則,Transloco 會把缺失鍵警告記錄到控制台。該設定還會停用增加開銷的開發期檢查。

路由導覽時譯文閃現

延遲載入路由會在元件渲染後才取得譯文,導致未翻譯的鍵短暫閃現。請使用 Transloco 內置的 TRANSLOCO_LOADING_TEMPLATE 顯示載入狀態,或在路由守衞中預載入譯文。

區域用戶看到英語而非父語言

Transloco 內置回退只在整個語言檔案缺失時觸發,不會處理單個缺失鍵。使用 angular-locale-chain 深度合併相關語言的譯文,例如 pt-BR 依次回退到 pt-PT、pt 和英語。

立即試用 i18n Agent

將翻譯檔案拖放到此處

JSON, YAML, PO, XML, CSV, Markdown, Properties

或點擊選擇檔案

目標語言

無需註冊即時估價

使用 angular-locale-chain 實現語言回退

如果 pt-BR 等區域語言缺少翻譯鍵,Angular 的 TranslocoLoader 會直接跳到預設語言,而不會先檢查父語言 pt。

Terminal
npm install angular-locale-chain
Configuration
import { LocaleChainLoader } from 'angular-locale-chain';

new LocaleChainLoader(innerLoader, {
  fallbacks: {
    'pt-BR': ['pt', 'en'],
    'zh-Hant-HK': ['zh-Hant', 'zh', 'en'],
  },
  defaultLocale: 'en',
});

查看語言回退指南,瞭解受支援框架的完整列表和 75 條內置回退鏈。 Learn more →

Angular i18n 常見問題