Transloco による Angular i18n:設定・翻訳ガイド
インストールから本番運用まで、Transloco の設定、ICU 構文による複数形処理、高度なロケールフォールバック、AI を活用した翻訳の自動化を解説します。
Transloco のインストール
Transloco は、Angular で最も広く利用されているサードパーティ製 i18n ライブラリです。実行時の翻訳読み込み、ICU メッセージ形式、遅延読み込みスコープに対応し、構造ディレクティブとパイプの両方を備えた簡潔なテンプレート API を提供します。
npm install @jsverse/translocoTransloco の設定
アプリケーション設定に 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 ファイルを 1 つずつ作成します。ネストしたキーを使用し、機能別に文字列を整理してください。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 では、テンプレート内で 3 通りの翻訳方法を利用できます。構造ディレクティブ(*transloco)、パイプ(| transloco)、TypeScript コード向けサービス(TranslocoService)です。構造ディレクティブは単一のサブスクリプションを作成し、テンプレートブロック全体に翻訳関数を提供するため、多くの用途で推奨されます。
テンプレートでの翻訳
<!-- 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 は、複数形と select 式に ICU メッセージ形式を使用します。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 →