(React 다국어 웹페이지 제작) 2. 다국어 변환을 도와주는 모듈 설치(react-i18next, i18next)


0. 모듈 설치

이제 React와 함께 사용하기 위해 국제화를 용이하게 하는 모듈을 설치해야 합니다.

react-i18next와 i18next 두 가지가 있습니다.

npm i react-18next i18next

공식 홈페이지에는 –save를 넣으라고 하는데 npm 5부터는 자동으로 의존성에 추가되기 때문에 따로 입력할 필요가 없습니다.

설치 후 JSON 파일을 확인합니다.


설치는 아주 순조롭게 진행되었습니다.

1. 기본 t 함수 사용법

위에서 설치한 모듈을 사용해보자.

기본 사용법은 다음과 같습니다.

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

i18n
  .use(initReactI18next)
  .init(
     // 여기에 내가 사용할 리소스 JSON 데이터를 넣으면 된다.
  )
  
function App() {
    const { t } = useTranslation();


    return (
    <div>{t("hello")}</div>
);

이 전체 프레임워크가 준비되면 아래 return 문에서 JSON 키를 t 함수에 넣습니다.

예를 들어 저쪽에 있는 JSON 데이터에 이것을 넣자.

{
  "resources": {
    "en": {
      "translation": {
        "hello": "Welcome to React and react-i18next!"
      }
    }
  },
  "lng": "en",
  "fallbackLng": "en",
  "interpolation": {
    "escapeValue": false
  }
}

이 JSON 데이터를 입력하면 키가 hello로 번역된 값이 출력됩니다.


실제 실행 화면

별도의 JSON으로 추출하여 구조화했습니다.

App.jsx 코드

import { useState } from "react";
// import reactLogo from './assets/react.svg'
import "./App.css";
import i18n from "i18next";
import { useTranslation, initReactI18next } from "react-i18next";
import languageJSON from "./json/language"

i18n
  .use(initReactI18next)
  .init(
      languageJSON
  )


function App() {
  const { t } = useTranslation();


  return (
    <div>{t("hello")}</div>
  );
}

export default App;

위의 코드를 보면 JSON 데이터가 languageJSON이라는 변수에 입력됩니다.

src/json/language.json 파일

{
  "resources": {
    "en": {
      "translation": {
        "hello": "Welcome to React and react-i18next!"
      }
    }
  },
  "lng": "en",
  "fallbackLng": "en",
  "interpolation": {
    "escapeValue": false
  }
}

나는 이렇게 썼다.

다음 포스팅에서는 다양한 언어로 번역해보도록 할게요,

해당 언어로 번역할 수 있는 버튼을 만들어 웹 앱을 만들어 봅시다.

2. 참고문헌

1. React-i18next 공식 홈페이지

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

시작하기 – react-i18next 문서

모듈은 웹팩, 롤업 등을 통해 로드하도록 최적화되어 있습니다. 올바른 진입점이 이미 package.json에 구성되어 있습니다. 최상의 빌드 옵션을 얻기 위해 추가 설정이 필요하지 않습니다.

react.i18next.com 웹사이트

끝.