1. 개요
React와 Next.js 기반의 웹 애플리케이션에서 다국어 지원(영어와 한국어)을 구현할 일이 생겨서 보통 어떤식으로 구현하는지 찾아보았다. 그 중 다국어 지원을 구현하기 위한 대표적인 라이브러리인 react-i18next의 사용법과 설정 방법에 대해서 간단히 알아보자.
2. react-i18next + next-i18next 세팅
GitHub - i18next/react-i18next: Internationalization for react done right. Using the i18next i18n ecosystem.
Internationalization for react done right. Using the i18next i18n ecosystem. - i18next/react-i18next
github.com
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
i18next
i18next internationalization framework. Latest version: 23.14.0, last published: 10 days ago. Start using i18next in your project by running `npm i i18next`. There are 6321 other projects in the npm registry using i18next.
www.npmjs.com
설명:
- react-i18next는 i18next의 React 버전으로, 다국어 지원을 위한 강력한 기능을 제공합니다.
- next-i18next는 Next.js와 react-i18next를 통합하여 SSR(서버 사이드 렌더링) 및 SSG(정적 사이트 생성)에서도 번역이 원활히 작동하도록 돕습니다.
주요 특징:
- JSON 파일 기반의 번역 관리.
- 서버 사이드 렌더링 지원.
- 사용자의 브라우저 언어 설정에 따라 자동으로 언어를 선택.
설치 및 설정:
npm install react-i18next i18next next-i18next
- next-i18next.config.js 파일 생성:
module.exports = {
i18n: {
defaultLocale: 'en',
locales: ['en', 'ko'],
},
};
- _app.js에서 appWithTranslation HOC 사용:
import { appWithTranslation } from 'next-i18next';
import '../styles/globals.css';
function MyApp({ Component, pageProps }) {
return <Component {...pageProps} />;
}
export default appWithTranslation(MyApp);
- next.config.js에 추가
const { i18n } = require('./next-i18next.config')
module.exports = {
i18n
}
번역 파일 예시:
- /public/locales/en/common.json
{
"welcome_message": "Welcome!"
}
- /public/locales/ko/common.json
{
"welcome_message": "환영합니다!"
}
컴포넌트에서 사용:
import { useTranslation } from 'react-i18next';
export const getServerSideProps: GetServerSideProps = async ({ locale }) => {
return {
props: {
...(await serverSideTranslations(
locale as string,
['common']
))
}
}
}
function MyComponent() {
const { t } = useTranslation('common');
return <h1>{t('welcome_message')}</h1>;
}
3. 번역 파일 작성
번역 파일은 각 언어별로 JSON 형식으로 작성합니다. 예를 들어, 영어와 한국어를 지원하려면 각 언어에 대한 JSON 파일을 생성해야 합니다.
번역 파일 예시:
- 영어 번역 파일 (public/locales/en/common.json):
{
"welcome_message": "Welcome!",
"goodbye_message": "Goodbye!"
}
- 한국어 번역 파일 (public/locales/ko/common.json):
{
"welcome_message": "환영합니다!",
"goodbye_message": "안녕히 가세요!"
}
이렇게 생성된 번역 파일을 기반으로, 애플리케이션에서 다국어 지원을 손쉽게 관리할 수 있습니다.
4. 언어 선택 기능 구현
사용자가 원하는 언어를 선택할 수 있는 UI를 제공하고, 선택된 언어에 따라 페이지가 번역된 텍스트를 보여주도록 구현합니다.
예시:
import { useRouter } from 'next/router';
function LanguageSwitcher() {
const router = useRouter();
const changeLanguage = (lang) => {
router.push(router.pathname, router.asPath, { locale: lang });
};
return (
<div>
<button onClick={() => changeLanguage('en')}>English</button>
<button onClick={() => changeLanguage('ko')}>한국어</button>
</div>
);
}
5. 번역파일 만들기 자동화
기존에 이미 한글로 제작되어있는 페이지를 이런식으로 다 바꾸는건 너무 노가다고 귀찮아서 찾아보니까 역시나 자동화도구가 있다.
i18next-scanner
i18next-scanner는 프로젝트에서 번역함수로 감싸진 텍스트를 자동으로 검색하고 i18n용 리소스 파일을 생성해주는 CLI 도구이다.
한글 -> 번역함수로 바꾸고 -> i18next-scanner 돌리면 번역 파일 만들어줌
https://github.com/i18next/i18next-scanner
GitHub - i18next/i18next-scanner: Scan your code, extract translation keys/values, and merge them into i18n resource files.
Scan your code, extract translation keys/values, and merge them into i18n resource files. - i18next/i18next-scanner
github.com
- 설치
npm install i18next-scanner --save-dev
- 설정 : i18next-scanner.config.js 파일을 생성하여 스캔할 파일과 생성할 리소스 파일의 경로를 설정
module.exports = {
input: ['src/**/*.{js,jsx}'],
output: './locales',
options: {
removeUnusedKeys: true,
debug: false,
},
};
- 사용 방법 : 터미널에서 다음 명령어를 실행하면 프로젝트 내 텍스트가 자동으로 스캔되고 번역 리소스 파일이 생성된다.
npx i18next-scanner
대규모 프로젝트나 다양한 언어와 팀 간 협업이 필요한 경우에는 i18next-scanner와 같은 도구를 사용해 초기 작업을 처리한 후, 전문 번역 플랫폼(예: Lokalise, Phrase)과 통합하여 번역 관리, 협업, 품질 보증을 강화하는 것이 좋다.
6. 결론
- React와 Next.js 기반의 애플리케이션에서 다국어 지원을 구현하려면, react-i18next와 next-i18next 라이브러리를 사용하는 것이 일반적입니다.
- 번역 파일을 작성해야 하며, 각 언어별로 관리합니다.
- i18next-scanner 같은 도구를 사용하면 번역 텍스트를 자동으로 추출하고 번역 키로 변환할 수 있습니다.
이렇게 설정된 다국어 지원 시스템을 통해 사용자는 원하는 언어로 페이지를 볼 수 있으며, 다양한 글로벌 사용자에게 서비스를 제공할 수 있다.
'💙Frontend' 카테고리의 다른 글
Paymentwall 해외 구독 결제 개발하기 (React, fastAPI) (1) | 2024.10.07 |
---|