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 파일을 하나씩 만드세요. 중첩 키를 사용해 기능별로 문자열을 구성하세요. 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)예요. 구조 지시문은 구독 하나만 만들고 전체 템플릿 블록에 번역 함수를 제공하므로 대부분의 경우에 권장해요.
템플릿 번역
<!-- 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-PT 번역이 있어도 pt-BR 사용자에게 영어가 표시돼요. 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 →