국제화 적용

이번에 기획하게 된 서비스인 Devrank는 Github 과 깊게 연관되어 있는 서비스이다. Github은 기본적으로 전 세계 사람이 사용하는 서비스이기 때문에 이번 프로젝트에 다국어 지원을 적용해보는 것이 어떻냐는 의견이 나왔고 팀원 모두 동의함에 따라 이번 프로젝트에 i18n을 도입해보기로 했다.

마스터님이 멘토링 때 국제화를 지원하는것과 지원하지 않는 코드가 많이 다르기 때문에 프로젝트 초기에 바로 적용하는 것이 좋다고 했고 개발에 들어가기 전 i18n을 바로 적용해보았다.

Next.js 국제화 설정

먼저 Next.js에서 i18n을 적용하는 것은 생각보다 간단하였다. Next.js에서는 i18n에 대한 라우팅을 내장으로 지원한다. 따라서 i18n 라이브러리와 라우팅을 이용한다면 쉽게 구현할 수 있다.

먼저 next.config.js에 다음과 같이 작성한다. 우리의 경우 한국어와 영어를 지원하고 한국어를 default로 설정하였다.

module.exports = {
  i18n: {
    // 어플리케이션에서 지원할 언어 리스트
    locales: ['en', 'ko'],
		// default로 설정할 locale
    defaultLocale: 'ko',
  },
};

이처럼 설정하면 Sub path routing으로 동작하여 hostname과 path사이에 locale이 들어간다. default locale일 경우 hostname과 path사이의 locale을 생략해도 된다.

<aside> 👉 Ex) http://localhost:3000/en/머시기머시기

</aside>

Sub path routing이 아닌 domain routing 또한 가능하다. 각 locale에 대한 domain을 아래와 같이직접 지정해주면 된다.

// next.config.js
module.exports = {
  i18n: {
    locales: ['en-US', 'fr', 'nl-NL', 'nl-BE'],
    defaultLocale: 'en-US',

    domains: [
      {
        // Note: subdomains must be included in the domain value to be matched
        // e.g. www.example.com should be used if that is the expected hostname
        domain: 'example.com',
        defaultLocale: 'en-US',
      },
      {
        domain: 'example.fr',
        defaultLocale: 'fr',
      },
      {
        domain: 'example.nl',
        defaultLocale: 'nl-NL',
        // specify other locales that should be redirected
        // to this domain
        locales: ['nl-BE'],
      },
    ],
  },
}

이외에도 여러가지 옵션들을 설정할 수 있다. 공식문서를 참고하자.

next-i18next

다음으론 next-i18next 라이브러리를 사용한다. 먼저 next-i18next 라이브러리를 설치하자.

yarn add next-i18next

Next.js의 public 폴더 아래에 locales 폴더를 생성하고 제공할 언어별로 폴더를 생성한다. 기본적으로 페이지별로 구분해서 번역 파일을 작성했고, 공통적인 부분은 common.json에서 관리하였다. 이 때 번역하느라 파파고의 힘을 많이 빌렸다..

.
└── public/
    └── locales/
        ├── ko/
        │   ├── common.json
        │   ├── index.json
        │   ├── about.json
        │   └── ranking.json
        └── en/
            ├── common.json
            ├── index.json
            ├── about.json
            └── ranking.json
// public/locales/ko
{
  "login-button": "로그인",
  "my-profile": "내 프로필",
  "logout": "로그아웃",
  "current-locale": "한국어",
  "table-tier": "티어",
  "table-user": "사용자",
  "table-score": "점수",
  "table-programming-lang": "언어",
  "table-user-num": "사용자수",
  "table-views": "조회수",
  "table-tech-stack": "기술스택"
}
// public/locales/en
{
  "login-button": "Login",
  "my-profile": "Profile",
  "logout": "Logout",
  "current-locale": "English",
  "table-tier": "Tier",
  "table-user": "User",
  "table-score": "Score",
  "table-programming-lang": "Lang",
  "table-user-num": "User number",
  "table-views": "Views",
  "table-tech-stack": "Tech Stack"
}

_app에 번역기능 적용하기