Next.js

[Next] i18n 사용법 with next-i18next

uni_i 2022. 11. 13. 23:06

1. 설치

yarn add next-i18next

npm install next-i18next

 

2. 사용법

(1) 루트 디렉토리에 next-18next.config.js 생성

module.exports = {
  i18n: {
    defaultLocale: "en",
    locales: ["en", "ko"], // 지원하는 locale 목록
  },
};

 

 

(2) public 폴더 → locales 폴더 → 각 언어 코드 폴더 (en, ko) → common.json

next.js 에서 i18n을 지원하고 있기 때문에, public/locales 라는 지정된 폴더 위치에 생성하면 됨. 

(3) next.config.js 에 next-18next.config.js 추가

/** @type {import('next').NextConfig} */

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

const nextConfig = {
  reactStrictMode: true,
  i18n,
};

module.exports = nextConfig;

(4) appWithTranslation 설정

_app.ts에서 설정. i18next provider를 추가하기 위해 필요.

import { appWithTranslation } from "next-i18next";

function MyApp({ Component, pageProps }) {
   ...
  return <Component {...pageProps} />;
}

export default appWithTranslation(MyApp);

 

(5) i18n을 쓸 페이지에 getStaticProps/getServerSideProps

정적 라우팅인지, 동적라우팅인지에 따라 getStaticProps/getServerSideProps 구분해서 사용하면 된다. 

import React, { useEffect } from "react";
import { serverSideTranslations } from "next-i18next/serverSideTranslations";
import { useTranslation } from "next-i18next";
export async function getStaticProps({ locale }) {
  console.log(locale);
  return {
    props: {
      ...(await serverSideTranslations(locale, ["common"])),
      // Will be passed to the page component as props
    },
  };
}
const I18nExample = () => {
  const { t } = useTranslation("common");
  return <p>{t("h1")}</p>;
};

export default I18nExample;

 

 

3. 주의점

  • 다른 페이지들이 추가 된다면, common.js 파일 대신 다른 파일명을 기입. common.js가 없으면 default damespace not required 에러가 나온다.
  • next는 서버 사이드 렌더링으로, 언어 코드 가져오는 것은 header 에 담긴 Accept-Language를 참조.
  • accept-language가 아닌 다른 언어로 바꾸고 싶으면 NEXT_LOCALE=the-locale 쿠키 이용(오버라이딩 가능)
  • next에서 i18n엔 사용시, sub-path로 accept-language에 있는 언어코드가 붙여짐.
  • hreflang이라는 meta/tag를 이용하여 seo 최적화 가능

 

 


참고 문서

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

 

GitHub - i18next/next-i18next: The easiest way to translate your NextJs apps.

The easiest way to translate your NextJs apps. Contribute to i18next/next-i18next development by creating an account on GitHub.

github.com