Language/Next.js

next-i18next 설치 및 사용법

  • -
반응형

다국어 지원을 위해서 i18n 라이브러리를 사용하게 되는데, 기존 리액트만 쓰게 될 경우 react-i18next 라이브러리를 많이 사용하게 된다.

다만 Next.js 를 쓰게 될 경우에는 react-i18next 도 사용 가능하지만 SSR(Server side Rendering)을 하려고 한다면 next-i18next 사용을 권장한다.

 

라이브러리

https://github.com/isaachinman/next-i18next

 

 

 

폴더 구조

 

 

폴더 구조는 라이브러리 샘플(https://github.com/isaachinman/next-i18next/tree/master/examples/simple) 예시 기준으로 작성하였다. 임의로 바꿔도 상관은 없다.

 

1. 먼저 해당 라이브러리를 설치

yarn add next-i18next 

혹은 npm install next-i18ext 

 

2. next.config.js 파일 생성 및 작성

const { i18n } = require("./next-i18next.config");

 

module.exports = {

i18n,

};

 

3. next-i18next.config.js 파일 생성 및 작성

module.exports = {

i18n: {

defaultLocale: "en",

locales: ["en", "ko"],

},

};

 

4. 해당 언어 파일 설정

예시 : public/locales/ko/common.json 와 public/locales/en/common.json 파일을 만든다.

{

"Racism Report App": "인종차별 보고서 앱",

"Home": "홈",

"List": "리스트",

"Video": "비디오",

"Static": "통계",

"Report": "신고",

"English": "영어",

"Korean": "한국어"

}

 

5. _app.js 파일에 추가 작성

import App from "next/app";

import { appWithTranslation } from "next-i18next";

 

 

....

const MyApp = (props) => {

const { Component, pageProps } = props;

 

return (

<Component {...pageProps} />

)


...

 

export default appWithTranslation(MyApp);

1.  라이브러리를 불러준다.

import { appWithTranslation } from "../i18n";

 

 

2. appWithTranslation으로 앱 자체를 감싸준다.

export default appWithTranslation(MyApp);

 

 

 

6. getStatpcProps 추가

예) pages/index.js

 

import { serverSideTranslations } from "next-i18next/serverSideTranslations";

export const getStaticProps = async ({ locale }) => ({

props: {

...(await serverSideTranslations(locale, ["common"])),

},

});

 

 

export default Home;

 

 


7. 번역하고 싶은 파일 번역하기

 

import { useTranslation } from "next-i18next";

 

 

const { t } = useTranslation("common");

 

return (

<Link href="/">

<Button color="inherit">{t("Home")}</Button>

</Link>

<Link href="/list">

<Button color="inherit">{t("List")}</Button>

</Link>

<Link href="/video">

<Button color="inherit">{t("Video")}</Button>

</Link>

<Link href="/statistics">

<Button color="inherit">{t("Static")}</Button>

</Link>

<Link href="/contact">

<Button color="inherit">{t("Report")}</Button>

</Link>

 

<Link href="/" locale="en">

<button>{t("English")}</button>

</Link>

<Link href="/" locale="ko">

<button>{t("Korean")}</button>

</Link>



 


1. useTranslation 을 불러와준다

2. const {t } = useTranslation ('common') 변수를 할당해줘서 바꾸고 싶은 텍스트에 {t("...")} 작성해준다

3. 만약 버튼을 통해서 언어를 바꾸고 싶다면 locale="en" 혹은 locale="ko" 버튼을 만들어준다. 그러면 버튼을 누르면 도메인 끝에 /ko가 추가로 붙으면서 한국어로 번역된다(default 가 영어기준)

 

결과 화면

 

동일글 네이버 블로그 참조

blog.naver.com/de24world/222196144182

반응형
Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.