[Next.js] next-i18next 사용 (언어팩)

Ahnjh·2022년 10월 9일
0

Next.js

목록 보기
3/4

개요

프로젝트 중 외국에도 서비스를 하는 제품이 있어서 next-i18next 를 써보게 됐다.

DOC : next-i18next/github

설정

설치

$ npm install next-i18next

구조

기본적으로 next-i18next 번역은 다음과 같이 구성되어야 한다

.
└── public
    └── locales
        ├── en
        |   └── common.json
        └── ko
            └── common.json

프로젝트 설정

먼저 프로젝트의 루트에 next-i18next.config.js 파일을 만든다

module.exports = {
  i18n: {
    defaultLocale: 'ko',
    locales: ['en', 'ko'],
  },
};

똑같이 프로젝트의 루트에 next.config.js파일을 만든다(있으면 추가)

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

module.exports = {
  i18n,
};

_app.js 수정

기존에 작성된 MyApp 을 내보낼때 appWithTranslation() 으로 감싸주기만 하면 된다.

import { appWithTranslation } from 'next-i18next';

const MyApp = ({ Component, pageProps }) => <Component {...pageProps} />;

export default appWithTranslation(MyApp);

common.js

common.js 에 다음과 같이 추가해준다

{
    "Title": "Subject"
}

언어 팩을 적용하고 싶은 페이지에서 다음과 같이 불러와준다

// login.js
export const getStaticProps = async ({ locale }) => {
    console.log("locale of getStaticProps", locale);
    return {
        props: {
            ...(await serverSideTranslations(locale, ["common"])),
        },
    };
};

export default function Home() {
    const { t } = useTranslation("common");
  
    return (
        <>
      		<h1>
      			{t("Title")}입니다 
            </h1>
        </>
    );
}

이후 localhost:3000/en/login 페이지를 확인해보면 common.js 에서 키벨류로 설정한 Title 값이 나오게된다

profile
Clean Code & Clean Architecture

0개의 댓글