使用 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 →