Skip to main content

Transloco를 활용한 Angular i18n: 설정 및 번역 가이드

설치부터 실제 서비스까지 Transloco를 구성하고, ICU 구문으로 복수형을 처리하고, 스마트 로케일 폴백을 추가하고, AI로 번역을 자동화하세요.

1

Transloco 설치

Transloco는 Angular에서 가장 인기 있는 타사 i18n 라이브러리예요. 런타임 번역 로드, ICU 메시지 형식, 지연 로드 범위, 구조 지시문과 파이프를 모두 갖춘 깔끔한 템플릿 API를 제공해요.

Angular 내장 i18n 대신 Transloco를 사용하는 이유는 무엇일까요? 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 {}
번역에 "Home" 대신 "nav.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)예요. 구조 지시문은 구독 하나만 만들고 전체 템플릿 블록에 번역 함수를 제공하므로 대부분의 경우에 권장해요.

템플릿 번역

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는 복수형과 select 표현식에 ICU 메시지 형식을 사용해요. 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-PT 번역이 있어도 pt-BR 사용자에게 영어가 표시돼요. 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 버그 #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 범위를 사용할 때 번역 파일은 루트 i18n 폴더가 아니라 assets/i18n/[scope]/[lang].json에 있어야 해요. TRANSLOCO_SCOPE를 사용해 컴포넌트의 providers 배열에 범위를 등록했는지도 확인하세요.

실제 서비스의 콘솔 경고

실제 서비스 빌드에서는 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 자주 묻는 질문