React에서 다국어 지원하기 (i18next, react-i18next)

하나의 웹에서 여러 국가의 언어를 지원하는 것은 흔히 볼 수 있는 케이스이다.

다만, 이것이 어떻게 구현되었는지 아는 것은 쉽지 않았는데 우연히 RN ignite를 사용해보고 어떻게 구현되었는지 알 수 있었다.

 

i18n-js 혹은 i18next와 같은 라이브러리를 사용하여 다국어를 지원하는 웹 사이트를 제작할 수 있다.

 

i18next

i18n-js보다 월등히 많이 사용되는 라이브러리로, 이를 통해서 다국어를 지원할 수 있다.

 

https://www.npmjs.com/package/i18next

 

i18next

i18next internationalization framework. Latest version: 22.4.15, last published: 14 days ago. Start using i18next in your project by running `npm i i18next`. There are 4799 other projects in the npm registry using i18next.

www.npmjs.com

 

react-i18next

리액트에서 i18next를 더 쉽게 사용할 수 있도록 훅을 지원해주는 라이브러리이다.

 

https://www.npmjs.com/package/react-i18next

 

react-i18next

Internationalization for react done right. Using the i18next i18n ecosystem.. Latest version: 12.2.2, last published: 9 days ago. Start using react-i18next in your project by running `npm i react-i18next`. There are 3514 other projects in the npm registry

www.npmjs.com

 

 

import { useEffect } from "react";
import i18n from "i18next";
import { useTranslation, initReactI18next } from "react-i18next";

i18n.use(initReactI18next).init({
  resources: {
    en: {
      translation: {
        "test phrase": "Pharase Test"
      }
    },
    ko: {
      translation: {
        "test phrase": "한국어 테스트"
      }
    }
  },
  lng: "en",
  fallbackLng: "en",
  interpolation: {
    escapeValue: false
  }
});

export default function App() {
  const { t, i18n } = useTranslation();
  useEffect(() => {
    i18n.changeLanguage("ko-kr");
    // i18n.changeLanguage("en-us");
  }, [i18n]);
  return (
    <div>
      <p>{t("test phrase")}</p>
    </div>
  );
}

 

위와 같이 i18n을 설정하고, React 환경에서 사용할 수 있다.

 

각 언어에 대한 설정은 Json 파일로 따로 관리할 수 있다.

{
  "test phrase": "한국어 테스트"
}

다만, Json 파일을 import 하기 위해서 타입스크립트에서는 "resolveJsonModule": true 설정이 필요하다.

 

https://react.i18next.com/getting-started

 

Getting started - react-i18next documentation

The module is optimized to load by webpack, rollup, ... The correct entry points are already configured in the package.json. There should be no extra setup needed to get the best build option.

react.i18next.com