PromleeBlog
sitemapaboutMe

posting thumbnail
i18next를 활용한 다국어 번역 구현하기 (React, Expo, React Native)
Implementing Multilingual Translation with i18next (React, Expo, React Native)

📅 2025년 03월 28일

🚀

들어가기 전에🔗

i18next란?🔗

image
i18next는 다국어 지원을 위한 자바스크립트 라이브러리로, React, React Native, Expo 등의 프로젝트에서 다국어 번역을 구현할 때 사용됩니다. i18next는 다양한 기능을 제공하며, 다국어 번역을 위한 효율적인 방법을 제공합니다.
Your software is using i18next? - Spread the word and let the world know!
오픈 소스 프로젝트를 진행 중이고 번역을 관리할 방법을 찾고 계신가요? - 로컬라이즈는 오픈 소스 철학을 지지하며 여러분을 지원할 수 있습니다. - i18next-introduction
성공적인 온라인 비즈니스를 운영하면서 다른 국가의 고객에게 도달하기 위해 비즈니스를 확장하고 싶다고 상상해 보세요. 이러한 시장에서 성공하려면 웹사이트나 앱이 해당 언어를 구사하고 각 지역의 문화를 이해해야 한다는 것을 알고 있을 것입니다. 이러한 이유로 다국어 지원은 매우 중요합니다.

🚀

il8next 설치🔗

먼저 아래 명령어를 실행하여 i18next 라이브러리를 설치합니다.
 # npm
npm install i18next --save
 
 # yarn
yarn add i18next

🚀

il8next 초기화🔗

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현재 언어 설정stringundefined
debug디버그 모드(로그) 활성화booleanfalse
resources번역 데이터objectundefined
fallbackLng언어 설정이 없을 때 사용할 언어
https://www.i18next.com/principles/fallback#language-fallback
string'en'

🚀

언어 팩 생성🔗

i18next를 사용하여 번역 데이터를 관리하고 언어 팩을 생성합니다. 번역 데이터는 resources 객체에 저장되며, lng 속성에 현재 언어를 설정합니다.
en-US.json
{
	"key": "value of key"
}
ko-KR.json
{
	"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 함수를 사용하여 번역 데이터를 가져올 수 있습니다.
en-US.json
{
	"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"
키 배열을 사용하여 t 함수를 호출하면 특정 폴백 값을 제공하지 않는 동적 키를 변환할 수 있습니다.
// 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 함수에 전달된 객체의 속성으로 대체됩니다.
en-US.json
{
    "key": "{{what}} is {{how}}"
}
i18next.t('key', { what: 'i18next', how: 'great' });
// -> "i18next is great"
전체 데이터 모델을 값으로 전달할 수도 있습니다.
en-US.json
{
    "key": "I am {{author.name}}"
}
const author = { 
    name: 'Jan',
    github: 'jamuhl'
};
i18next.t('key', { author });
// -> "I am Jan"

포맷팅 사용법🔗

i18next는 설정법에 따른 포맷팅을 지원합니다. 숫자, 날짜, 통화 등을 포맷팅할 수 있습니다. 조금 복잡하니 i18next 포맷팅을 참고하며 따라와주세요.
기본적인 형태는 다음과 같습니다.
다음은 기본으로 제공되는 포맷팅 방법입니다.
➡️

숫자 포맷팅 - number🔗

number 포맷팅은 숫자를 포맷팅합니다.
formatnamenumber이며 minimumFractionDigits옵션은 소수점 이하 자릿수를 설정합니다.
en-US.json
{
	"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🔗

currency 포맷팅은 통화를 포맷팅합니다.
formatnamecurrency이며 currency옵션은 통화 코드를 설정합니다.
en-US.json
{
  "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🔗

datetime 포맷팅은 날짜/시간을 포맷팅합니다.
formatnamedatetime이며 format옵션은 날짜/시간 형식을 설정합니다.
en-US.json
{
  "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🔗

list 포맷팅은 배열을 포맷팅합니다.
formatnamelist이며 type옵션은 리스트 형식을 설정합니다.
en-US.json
{
  "intlList": "A list of {{val, list}}"
}
// JSON
i18next.t('intlList', { val: ['locize', 'i18next', 'awesomeness'] });
// --> A list of locize, i18next, and awesomeness

단/복수형 사용법🔗

🖐️
반드시 count 변수를 사용하여 단/복수형을 구분해야 합니다.
➡️

기본 단/복수 형식🔗

i18next는 단/복수형을 지원합니다. key에 _one 또는 _other를 추가하여 단/복수형을 구분할 수 있습니다.
en-US.json
{
  "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"
➡️

또 다른 방법🔗

one 이외에는 총 5가지의 표현 방법이 있습니다.
en-US.json
{
  "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 (구글 번역기 베이스라고 합니다.)

참고🔗