국제화와 현지화 (Internationalization and Localization)
컴포넌트 메시지를 번역하고 날짜 형식, 한 주의 시작 요일 같은 지역 설정을 구성하는 방법을 알려드릴게요. 여러 언어를 지원하는 앱을 만들 때 필수로 알아야 할 부분이에요.
출처: 문서
본문
개요 (Overview)
컴포넌트는 필터 연산자 라벨, 월 이름, ARIA 설명 같은 기본 제공 메시지를 함께 배포해요. 이 메시지들은 @primeuix/locale 패키지를 통해 PrimeReact, PrimeVue, PrimeNG에서 공유되는 로케일 레지스트리에 있고, @primereact/core/locale에서 다시 export돼요.
기본적으로 영어가 등록되어 있어서, 다른 언어가 필요해지기 전까지는 설정이 필요 없어요.
언어를 설정하는 것만으로 컴포넌트가 그 언어를 사용해요. 컴포넌트별 prop은 관여하지 않아요. 아래에서 언어를 바꾸면 캘린더가 번역된 월·요일 이름으로 다시 렌더링되고, 한 주의 시작 요일이 이동하며, 버튼 라벨도 갱신돼요.
Import
import { $t, $l, defineLocale, updateLocale, useLocale, Locale, LocaleService, en } from '@primereact/core/locale';
언어 설정 (Setting the Language)
Locale.use가 활성 언어를 선택해요. 메시지를 읽는 모든 컴포넌트는 언어가 바뀌면 다시 렌더링되므로, 시작 시점과 언어 스위처에 대한 응답으로 모두 동작해요.
import { Locale } from '@primereact/core/locale';
Locale.use('de');
en만 내장되어 있어서, 다른 언어는 먼저 등록해야 해요. 아래 언어 추가를 참고하세요.
PrimeReactProvider도 locale prop을 받아서, 그 아래 컴포넌트들의 초기 언어를 설정해요.
import { PrimeReactProvider } from '@primereact/core';
<PrimeReactProvider locale="de">
<App />
</PrimeReactProvider>;
언어 추가 (Adding a Language)
defineLocale이 새 언어를 등록해요.
import { defineLocale, Locale } from '@primereact/core/locale';
defineLocale('es', {
clear: 'Limpiar',
apply: 'Aplicar',
accept: 'Sí',
reject: 'No',
dayNames: ['domingo', 'lunes', 'martes', 'miércoles', 'jueves', 'viernes', 'sábado'],
dayNamesShort: ['dom', 'lun', 'mar', 'mié', 'jue', 'vie', 'sáb'],
dayNamesMin: ['D', 'L', 'M', 'X', 'J', 'V', 'S'],
monthNames: ['enero', 'febrero', 'marzo', 'abril', 'mayo', 'junio', 'julio', 'agosto', 'septiembre', 'octubre', 'noviembre', 'diciembre'],
monthNamesShort: ['ene', 'feb', 'mar', 'abr', 'may', 'jun', 'jul', 'ago', 'sep', 'oct', 'nov', 'dic']
});
Locale.use('es');
등록된 언어는 완전해야 해요. 빠뜨린 키는 영어로 폴백되지 않고 undefined로 해석되며, 빈 라벨로 렌더링돼요. 실용적인 방법은 내장 영어 메시지를 펼치고 거기서 덮어쓰는 거예요:
import { defineLocale, en } from '@primereact/core/locale';
defineLocale('es', {
...en,
clear: 'Limpiar',
apply: 'Aplicar'
});
en 객체는 내장 영어 메시지를 담고 있으며 정확히 이 목적으로 export돼요. PrimeLocale의 준비된 번역은 이미 모든 키를 다루므로, 펼치기는 수작업 번역에서만 필요해요.
Provider는 locales 맵을 받아서 언어를 등록하고 하나를 선택하는 것을 한 번에 처리해요. 여기에 나열된 것은 locale이 적용되기 전에 전부 등록돼요.
import { PrimeReactProvider } from '@primereact/core';
<PrimeReactProvider locale="es" locales={{ es: spanishMessages }}>
<App />
</PrimeReactProvider>;
기존 언어 갱신 (Updating an Existing Language)
updateLocale은 이미 등록된 언어에 새 값을 병합하고, 나머지 키는 그대로 둬요. 전체 번역을 재정의하지 않고 몇몇 라벨을 덮어쓸 때 유용해요.
import { updateLocale } from '@primereact/core/locale';
updateLocale('en', {
clear: 'Reset',
apply: 'Confirm'
});
언어가 아직 없으면 updateLocale이 defineLocale처럼 동작하며 등록해요.
메시지 읽기 (Reading Messages)
컴포넌트 안에서 (In Components)
useLocale은 활성 로케일을 읽는 React 훅이에요. 언어가 바뀌면 호출 컴포넌트를 다시 렌더링해요.
import { Button } from '@primereact/ui/button';
import { useLocale } from '@primereact/core/locale';
function ClearFilterButton({ onClear }) {
const { t } = useLocale();
return (
<Button severity="secondary" onClick={onClear}>
{t('clear')}
</Button>
);
}
| Field | Description |
|---|---|
lang |
Active language code, such as en or de. |
messages |
Full message object of the active language. |
t |
Translates a key against the active language. |
언어 변경 시 재렌더링은 애플리케이션이 보통 루트에 두는 PrimeReactProvider가 게시하는 컨텍스트에 의존해요. 어떤 provider 밖에서 렌더링된 컴포넌트는 첫 렌더링에서는 올바른 메시지를 읽지만, 이후 언어가 바뀌어도 갱신되지 않아요.
컴포넌트 밖에서 (Outside Components)
$t는 React 컨텍스트 없이 동일한 조회를 수행해서, 유틸리티, 이벤트 핸들러, 모듈 레벨 코드에 적합해요.
import { $t } from '@primereact/core/locale';
$t('clear'); // 'Clear'
중첩 키는 점 표기법을 사용해요.
$t('aria.selectRow'); // 'Row Selected'
플레이스홀더를 포함한 메시지는 대체 값을 받아요. {0} 같은 위치 플레이스홀더는 인자 순서로 채워지고, 이름 있는 것은 객체로 채워져요.
$t('searchMessage', 5); // '5 results are available'
$t('selectionMessage', 3); // '3 items selected'
$t('aria.stars', { star: 4 }); // '4 stars'
언어 변경 반응 (Reacting to Language Changes)
언어 변경은 locale:change 이벤트를 발생시켜요. 컴포넌트는 useLocale로 이를 자동 처리하며, 이 이벤트는 제3자 라이브러리를 동기화하는 것처럼 React 밖에 있는 코드에서만 필요해요.
import { LocaleService } from '@primereact/core/locale';
const onChange = ({ lang }) => console.log('Language is now', lang);
LocaleService.on('locale:change', onChange);
// remove the listener when it is no longer needed
LocaleService.off('locale:change', onChange);
레지스트리 검사 (Inspecting the Registry)
$l은 레지스트리에 대한 파사드를 반환해서, 언어 스위처를 만들 때 도움이 돼요.
import { $l } from '@primereact/core/locale';
$l().langs; // ['en', 'es']
$l().get('es'); // message object of the Spanish locale
메시지 키 (Message Keys)
이 컴포넌트들은 활성 언어에서 라벨을 읽어요:
| Component | Keys |
|---|---|
| DatePicker | dayNames, dayNamesShort, dayNamesMin, monthNames, monthNamesShort, today, weekHeader, clear, am, pm, firstDayOfWeek, dateFormat |
| FileUpload | fileSizeTypes |
| Paginator | aria.firstPageLabel, aria.prevPageLabel, aria.nextPageLabel, aria.lastPageLabel, aria.pageLabel |
| Sidebar | aria.toggleSidebar |
레지스트리는 필터 연산자, 비밀번호 강도 라벨, 빈 상태 메시지, 나머지 aria 라벨을 포함하는 더 큰 집합을 담아요. 이들은 아직 그것을 소비하지 않는 컴포넌트를 위해 예약되어 있어서, 번역해도 지금은 눈에 보이는 효과가 없어요.
모든 항목이 문자열은 아니에요. firstDayOfWeek는 숫자, showMonthAfterYear는 불리언, dayNames, monthNames, fileSizeTypes는 배열이에요. searchMessage 같은 항목은 {0} 플레이스홀더를 담아요.
기본 영어 값을 포함한 전체 집합은 en으로 export되며, 런타임에서도 검사할 수 있어요:
import { en } from '@primereact/core/locale';
Object.keys(en); // every top-level key
준비된 번역 (Ready-Made Translations)
번역을 처음부터 쓰는 일은 거의 필요 없어요. 커뮤니티 관리 PrimeLocale 저장소는 모든 Prime 라이브러리에서 공유되는 70개 이상 언어의 완전한 번역을 게시해요. 각 파일이 모든 내장 메시지 키를 다루므로, 아무것도 undefined로 해석되지 않아요.
파일 복사 (Copying a File)
저장소에서 원하는 언어의 JSON 파일(예: es.json)을 가져와 프로젝트에 배치해요.
각 파일은 메시지를 언어 이름을 딴 단일 키로 감싸요:
{
"es": {
"clear": "Limpiar",
"apply": "Aplicar",
"aria": { "selectRow": "Seleccionar fila" }
}
}
그 래퍼는 등록하기 전에 풀어야 해요. 그렇지 않으면 모든 조회가 undefined로 해석돼요:
import { defineLocale, Locale } from '@primereact/core/locale';
import es from './locales/es.json';
defineLocale('es', es.es);
Locale.use('es');
Provider를 통해 등록할 때도 같은 풀기(unwrapping)가 적용돼요:
import { PrimeReactProvider } from '@primereact/core';
import es from './locales/es.json';
<PrimeReactProvider locale="es" locales={{ es: es.es }}>
<App />
</PrimeReactProvider>;
패키지 설치 (Installing the Package)
번역은 npm에도 게시되어 있어서, 사본을 수작업으로 관리하지 않아도 돼요.
npm install primelocale
import { defineLocale, Locale } from '@primereact/core/locale';
import { es } from 'primelocale/js/es.js';
defineLocale('es', es);
Locale.use('es');
패키지 엔트리 포인트는 메시지를 직접 export하므로, 여기서는 풀기가 필요 없어요.
지역 변형(variant)은 패키지에서는 밑줄, JSON 파일에서는 하이픈으로 이름을 붙여요. 브라질 포르투갈어는 import할 때 primelocale/js/pt_BR.js, 복사할 때 pt-BR.json이에요.
번역 조정 (Adjusting a Translation)
준비된 번역은 파일을 편집하지 않고도 그 위에 오버라이드를 겹쳐서 조정할 수 있어요:
defineLocale('es', es.es);
updateLocale('es', { clear: 'Borrar' });
새 언어와 수정 사항에 대한 기여는 PrimeLocale 저장소에서 환영하며, 모든 Prime 라이브러리에 동시에 이득이 돼요.
v10에서 오는 경우 (Coming from v10)
primereact/api의 로케일 헬퍼는 교체됐어요. 마이그레이션 가이드가 각각의 대체 항목을 매핑해 줘요.
더 알아보기 (Learn more)
defineLocale,updateLocale,useLocale의 차이를 각 사용 사례에 맞게 정리해 보세요.- PrimeLocale 저장소에서 70개 이상 언어의 준비된 번역을 활용해 보세요.