i18next
는 다국어 지원을 위한 자바스크립트 라이브러리로, React, React Native, Expo 등의 프로젝트에서 다국어 번역을 구현할 때 사용됩니다. i18next
는 다양한 기능을 제공하며, 다국어 번역을 위한 효율적인 방법을 제공합니다.Your software is using i18next? - Spread the word and let the world know! 오픈 소스 프로젝트를 진행 중이고 번역을 관리할 방법을 찾고 계신가요? - 로컬라이즈는 오픈 소스 철학을 지지하며 여러분을 지원할 수 있습니다. - i18next-introduction↗
i18next
라이브러리를 설치합니다. # npm
npm install i18next --save
# yarn
yarn add i18next
i18next
를 초기화하고 번역 데이터를 설정합니다. i18next
를 초기화하려면 i18next
객체를 생성하고 번역 데이터를 설정해야 합니다.import i18next from 'i18next';
await i18next.init({
lng: 'en',
debug: true,
resources: {
en: {
translation: {
"key": "hello world"
}
}
}
});
console.log(i18next.t('key'));
i18next
초기화 옵션은 다음과 같습니다. 더 많은 옵션은 i18next 초기화 옵션↗을 참고하세요.옵션 | 설명 | 타입 | 기본값 |
---|---|---|---|
lng | 현재 언어 설정 | string | undefined |
debug | 디버그 모드(로그) 활성화 | boolean | false |
resources | 번역 데이터 | object | undefined |
fallbackLng | 언어 설정이 없을 때 사용할 언어 https://www.i18next.com/principles/fallback#language-fallback↗ | string | 'en' |
i18next
를 사용하여 번역 데이터를 관리하고 언어 팩을 생성합니다. 번역 데이터는 resources
객체에 저장되며, lng
속성에 현재 언어를 설정합니다.{
"key": "value of key"
}
{
"key": "키 값"
}
import i18next from 'i18next';
import translationEn from "./en-US.json";
import translationKo from "./ko-KR.json";
await i18next.init({
lng: 'en', // 언어 설정은 여기서 변경
debug: true,
resources: {
en: {
translation: translationEn
},
ko: {
translation: translationKo
}
}
});
console.log(i18next.t('key')); // "value of key"
console.log(i18next.t('key', { lng: 'ko' })); // "키 값"
i18next
를 사용하여 번역 데이터를 가져와 사용합니다. i18next.t
함수를 사용하여 번역 데이터를 가져올 수 있습니다.{
"key": "value of key",
"look": {
"deep": "value of look deep"
},
"error": {
"unspecific": "Something went wrong.",
"404": "The page was not found."
}
}
i18next.t('key'); // "value of key"
i18next.t('look.deep'); // "value of look deep"
i18next.t('notkey', 'default value to show'); // "default value to show"
// const error = '404';
i18next.t([`error.${error}`, 'error.unspecific']); // -> "The page was not found"
// const error = '502';
i18next.t([`error.${error}`, 'error.unspecific']); // -> "Something went wrong"
i18next.t
함수에 전달된 객체의 속성으로 대체됩니다.{
"key": "{{what}} is {{how}}"
}
i18next.t('key', { what: 'i18next', how: 'great' });
// -> "i18next is great"
{
"key": "I am {{author.name}}"
}
const author = {
name: 'Jan',
github: 'jamuhl'
};
i18next.t('key', { author });
// -> "I am Jan"
i18next
는 설정법에 따른 포맷팅을 지원합니다. 숫자, 날짜, 통화 등을 포맷팅할 수 있습니다. 조금 복잡하니 i18next 포맷팅↗을 참고하며 따라와주세요.
기본적인 형태는 다음과 같습니다.{{value, formatname(options1: options1Value)}}
: value
를 formatname
으로 포맷팅합니다.t('key', { option1: option1Value })
: 루트 옵션으로 포맷팅을 설정합니다.t('key', { formatParams: { value: { option1: option1Value } })
: value
별로 다른 포맷팅을 설정합니다.number
포맷팅은 숫자를 포맷팅합니다.
formatname
은 number
이며 minimumFractionDigits
옵션은 소수점 이하 자릿수를 설정합니다.{
"intlNumber": "Some {{val, number}}",
"intlNumberWithOptions": "Some {{val, number(minimumFractionDigits: 2)}}"
}
i18next.t('intlNumber', { val: 1000 });
// --> Some 1,000
i18next.t('intlNumber', { val: 1000.1, minimumFractionDigits: 3 });
// --> Some 1,000.100
i18next.t('intlNumber', { val: 1000.1, formatParams: { val: { minimumFractionDigits: 3 } } });
// --> Some 1,000.100
i18next.t('intlNumberWithOptions', { val: 2000 });
// --> Some 2,000.00
i18next.t('intlNumberWithOptions', { val: 2000, minimumFractionDigits: 3 });
// --> Some 2,000.000
// 다국어 설정
i18next.t('intlNumber', { val: 1000.1, lng: 'de' });
// or: i18next.t('intlNumber', { val: 1000.1, locale: 'de' });
i18next.t('intlNumber', { val: 1000.1, formatParams: { val: { lng: 'de' } } });
// or: i18next.t('intlNumber', { val: 1000.1, formatParams: { val: { locale: 'de' } } });
currency
포맷팅은 통화를 포맷팅합니다.
formatname
은 currency
이며 currency
옵션은 통화 코드를 설정합니다.{
"intlCurrencyWithOptionsSimplified": "The value is {{val, currency(USD)}}",
"intlCurrencyWithOptions": "The value is {{val, currency(currency: USD)}}",
"twoIntlCurrencyWithUniqueFormatOptions": "The value is {{localValue, currency}} or {{altValue, currency}}",
}
i18next.t('intlCurrencyWithOptionsSimplified', { val: 2000 });
// --> The value is $2,000.00
i18next.t('intlCurrencyWithOptions', { val: 2300 });
// --> The value is $2,300.00
i18next.t('twoIntlCurrencyWithUniqueFormatOptions',
{
localValue: 12345.67,
altValue: 16543.21,
formatParams: {
localValue: { currency: 'USD', locale: 'en-US' },
altValue: { currency: 'CAD', locale: 'fr-CA' },
},
},);
// --> The value is $12,345.67 or 16 543,21 $ CA
datetime
포맷팅은 날짜/시간을 포맷팅합니다.
formatname
은 datetime
이며 format
옵션은 날짜/시간 형식을 설정합니다.{
"intlDateTime": "On the {{val, datetime}}",
}
i18next.t('intlDateTime', { val: new Date(Date.UTC(2012, 11, 20, 3, 0, 0)) });
// --> On the 12/20/2012
i18next.t('intlDateTime',
{
val: new Date(Date.UTC(2012, 11, 20, 3, 0, 0)),
formatParams: {
val: { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' },
},
});
// --> On the Thursday, December 20, 2012
list
포맷팅은 배열을 포맷팅합니다.
formatname
은 list
이며 type
옵션은 리스트 형식을 설정합니다.{
"intlList": "A list of {{val, list}}"
}
// JSON
i18next.t('intlList', { val: ['locize', 'i18next', 'awesomeness'] });
// --> A list of locize, i18next, and awesomeness
i18next
는 단/복수형을 지원합니다. key에 _one
또는 _other
를 추가하여 단/복수형을 구분할 수 있습니다.{
"key_one": "item",
"key_other": "items",
"keyWithCount_one": "{{count}} item",
"keyWithCount_other": "{{count}} items"
}
i18next.t('key', {count: 0}); // -> "items"
i18next.t('key', {count: 1}); // -> "item"
i18next.t('key', {count: 5}); // -> "items"
i18next.t('key', {count: 100}); // -> "items"
i18next.t('keyWithCount', {count: 0}); // -> "0 items"
i18next.t('keyWithCount', {count: 1}); // -> "1 item"
i18next.t('keyWithCount', {count: 5}); // -> "5 items"
i18next.t('keyWithCount', {count: 100}); // -> "100 items"
_zero
: 0_one
: 1_two
: 2_few
: 3~10_many
: 11~99_other
: 100~{
"key_zero": "zero",
"key_one": "singular",
"key_two": "two",
"key_few": "few",
"key_many": "many",
"key_other": "other"
}
i18next.t('key', {count: 0}); // -> "zero"
i18next.t('key', {count: 1}); // -> "singular"
i18next.t('key', {count: 2}); // -> "two"
i18next.t('key', {count: 3}); // -> "few"
i18next.t('key', {count: 4}); // -> "few"
i18next.t('key', {count: 5}); // -> "few"
i18next.t('key', {count: 11}); // -> "many"
i18next.t('key', {count: 99}); // -> "many"
i18next.t('key', {count: 100}); // -> "other"
i18next
를 사용하여 Typescript에서 i18next
는 다양한 기능을 제공하며, 다국어 번역을 위한 효율적인 방법을 제공합니다. 번역 데이터를 관리하고 언어 팩을 생성하는 방법을 알아보았으며, 번역 데이터를 가져와 사용하는 방법을 알아보았습니다. 이제 i18next
를 사용하여 다국어 번역을 구현할 수 있습니다.
각 프론트엔드 플랫폼에서 i18next
를 사용하는 방법은 다소 다를 수 있으므로, 해당 플랫폼의 문서를 참고하여 구현해보세요. 관련 라이브럴리도 많이 있으니 찾아보시면 도움이 될 것입니다. i18next - supported-frameworks↗
또한 il8n에서 제공하는 json 자동 번역 사이트를 이용하면 번역 데이터를 쉽게 생성할 수 있습니다. translate.i18next↗ (구글 번역기 베이스라고 합니다.)