0. 모듈 설치
이제 react에서 사용할 국제화를 도울 모듈을 설치해야한다.
2개인데 react-i18next와 i18next이다.
npm i react-18next i18next
공식 사이트에는 --save를 넣으라고 하지만, npm 5 버전부터는 자동으로 dependency에 추가해주기 때문에 입력할 필요가 없다.
설치된 이후에 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>
);
이렇게 전체적인 틀을 잡고, 우리는 아래에 리턴문에 있는 t 함수에 JSON의 key를 넣어줄 것이다.
예를 들어 저기 JSON 데이터에 이렇게 넣어보자.
{
"resources": {
"en": {
"translation": {
"hello": "Welcome to React and react-i18next!"
}
}
},
"lng": "en",
"fallbackLng": "en",
"interpolation": {
"escapeValue": false
}
}
이런 JSON 데이터가 들어가면, translation에 있는 키가 hello인 값(value)을 출력한다.
나는 이것을 별도의 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;
위의 코드를 보면 languageJSON 이라는 변수에 JSON 데이터를 가지고 오고 있다.
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
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
끝.