使用 Transloco 實現 Angular i18n:設定與翻譯指南
從安裝到生產:設定 Transloco、使用 ICU 語法處理複數、新增智能語言回退,並利用 AI 自動翻譯。
安裝 Transloco
Transloco 是 Angular 最流行的第三方 i18n 庫,提供執行階段譯文載入、ICU 訊息格式支援、延遲載入的作用域,以及同時支援結構指令和管道的簡潔範本 API。
npm install @jsverse/transloco設定 Transloco
在應用程式設定中註冊 Transloco。你需要提供可用語言、設定預設語言並設定譯文載入器。Transloco 同時支援獨立元件(Angular 14+)和 NgModule 模式。
獨立元件(推薦)
// 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
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 {}建立翻譯檔案
在 src/assets/i18n/ 中為每種語言建立一個 JSON 檔案。使用嵌套鍵按功能組織字串。Transloco 使用 ICU 訊息格式處理複數和變數。
// 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}}"
}
}在範本和服務中使用譯文
Transloco 提供三種範本翻譯方式:結構指令(*transloco)、管道(| transloco),以及供 TypeScript 程式碼使用的服務(TranslocoService)。大多數場景推薦結構指令,因為它只建立一個訂閱,並將 translate 函數提供給整個範本塊。
範本翻譯
<!-- 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>服務翻譯(TypeScript)
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);
}
}使用 ICU 訊息格式處理複數
Transloco 使用 ICU 訊息格式處理複數和 select 表達式。ICU 可自動處理複雜複數規則,包括阿拉伯語 6 種形式、俄語 3 種、日語 1 種,全部來自單個訊息字串。請在翻譯檔案中定義複數規則,Transloco 會在執行階段選擇正確形式。
// 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>使用 angular-locale-chain 實現智能語言回退
預設情況下,缺少翻譯鍵時 Transloco 會回退到預設語言。pt-BR 用戶會看到英語,而不是完全可用的 pt-PT 譯文。angular-locale-chain 會先深度合併可設定回退鏈中的譯文,再交給 Transloco,確保每個鍵都有內容,不留缺口或缺失譯文。
npm install angular-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(),
},
],
};推薦的檔案結構
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 實現全自動本地化。
# 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 Agent
將翻譯檔案拖放到此處
JSON, YAML, PO, XML, CSV, Markdown, Properties
或點擊選擇檔案
目標語言
使用 angular-locale-chain 實現語言回退
如果 pt-BR 等區域語言缺少翻譯鍵,Angular 的 TranslocoLoader 會直接跳到預設語言,而不會先檢查父語言 pt。
npm install angular-locale-chainimport { 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 →