react-i18n 파일 분리 하기

상현·2024년 1월 25일
post-thumbnail

개요

react-i18n 라이브러리 사용 중 번역해야 할 언어와 문장, 단어가 많아질수록 파일을 분리하는 것이 더 낫다고 생각했고, 라이브러리 공식 홈페이지에서도 파일을 분리하는 방법을 추천하고 있다.

패키지 설치

파일을 통해 i18n을 사용하기 위해서는 추가적인 패키지 설치가 필요하다.

$ yarn add i18next-http-backend

locales 폴더 생성

파일은 json 파일로 생성할 것이며, 언어별로 폴더를 분리할 것이다. public/locales/ko 와 같이 폴더 구조를 만들어보자. 그리고 각 폴더안에 translation.json 이라는 파일을 만든다.

그리고 파일 안에 다음과 같이 내용을 채워준다.

// ko/translation.json
{
  "order-type-title-1": "매장식사 또는",
  "order-type-title-2": "포장을 선택해 주세요.",
  "order-type-store": "먹고 갈게요",
  "order-type-togo": "포장 할게요"
}

// en/translation.json
{
  "order-type-title-1": "Please choose",
  "order-type-title-2": "store meal or takeout",
  "order-type-store": "Eat it at the store",
  "order-type-togo": "Wrap it up"
}

i18n.ts 수정

그리고 설정 파일인 i18n.ts 파일을 다음과 같이 수정해준다.

import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
// load translation using http -> see /public/locales
import Backend from 'i18next-http-backend';

i18n
  .use(initReactI18next)
  .use(Backend)
  .init({
    lng: 'en',
    interpolation: {
      escapeValue: false, // react already safes from xss
    },
  });

export default i18n;

그럼 이제 라이브러리가 자동으로 폴더를 찾아서 초기화를 해준다!

profile
블로그 이전 => https://shdev.blog/

0개의 댓글