Next.js에서 다국어처리하기

Hoon·2023년 9월 1일
0

Next.js

목록 보기
3/3
post-thumbnail

Next.js 으로 만든 프로젝트에서 한국어영어 를 지원해야할 내용이있어 사용했던 부분을 정리해볼려고한다. next-i18next 이란 라이브러리를 사용해서 처리하였다.

i18n 이란?

응용 프로그램을 다양한 지역에 맞게 조정하는 시스템이며 next-i18next는 자바스크립트에서 언어 변환등의 국제화(i18n)처리를 가능하게 해주는 라이브러리입니다

Install

$ npm install --save next-i18next
$ yarn add next-i18next

Setting

// next-18next.config.js
const path = require('path')

const config = {
    i18n: {
        defaultLocale: 'ko',
        locales: ['ko', 'en'],
        defaultNS: 'common',
        localeDetection: true,
        localePath: path.resolve('./public/locales') // 다국어 파일 경로
    },
};

module.exports = config;

먼저 프로젝트에 next-18next.config.js 라는 파일을 만들어 i18n 에 대한 기본적인 셋팅을 해준뒤 next.config.js 에 포함시켜주었다.

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

const nextConfig = {
  // ...nextConfigOption,
  i18n
}

module.exports = nextConfig

json 파일 생성

next-18next.config.js 에서 넣어주었던 ./public/locales path에 ko, en 이라는 폴더를 각각 만들어준 뒤 각 국가에 대한 텍스트를 저장할 json 파일을 생성해준다.

// home.json (ko)
{
  "title": "제목",
  "sub-title" : "부제목",
  "content" : "내용",
  "submit-button" : "제출"
}
// home.json (en)
{
  "title": "Title",
  "sub-title" : "Sub Title",
  "content" : "Content",
  "submit-button" : "Submit"
}

Try

아래와 같이 getStaticpropsserverSideTranslations 통해서 locale 정보를 넘겨주었고, 페이지내에서는 useTranslation 훅을 통해서 해당 json 에 반환된 값을 사용하였다.

// index.tsx
import { useTranslation } from 'next-i18next';
import { serverSideTranslations } from 'next-i18next/serverSideTranslations';

const Home: NextPage = () => {
  	const { t } = useTranslation('home');
  
    return (
      <div>
        <h1>{t('title')}</h1>
        <h3>{t('sub-title')}</h3>
        <p>{t('content')}</p>
        <button>{t('submit-button')}</button>
      </div>
    )
}

export const getStaticProps = async ({ locale }: any) => ({
  props: {
    ...(await serverSideTranslations(locale, ['home'])),
  },
});

export default Home;

이렇게 작성된 프로젝트는 /, /ko 로 들어오면 default locale로 설정해준 한국어로, /en 으로 들어오면 영어 로 보여준다.

/list, /detail 과 같은 페이지에서도 /en/list, /en/detail 와 마찬가지로 작용한다.

profile
개발자 Hoon입니다

0개의 댓글