Next JS에 i18n 다국어 적용하기
Next JS에 i18n 다국어 적용하기
Next JS 14 프로젝트에 next-intl 라이브러리를 사용해 i18n 다국어를 적용해보자
Next.js 14next-intl다국어i18n
282 views
next-intl이란?
Next.js 애플리케이션에서 다국어 지원을 쉽게 구현할 수 있도록 돕는 라이브러리로, Next JS 에서의 다국어 작업을 간편하게 만들어 준다.
주요 기능은 다음과 같다.
- ICU 메세지 형식 사용
- 다국어 텍스트 관리 - 각 언어의 대한 번역 파일을 동적으로 관리한다.
- Hook 기반 API 제공 - SSR, CSR 에서 사용할 수 있는 Hook을 둘 다 제공한다.
- 성능 - Next.js 원천 기능을 활용하며 성능에 집중했다.
적용 방법
설치
npm install next-intl
디렉토리 구조 (app 라우팅 기준)
└───app
│ ├───[locale]
│ │ page.tsx
│ │
├───messages
│ en.json
│ ko.json
Next JS 설정 파일에 플러그인 추가
// next.config.js
const createNextIntlPlugin = require('next-intl/plugin');
const withNextIntl = createNextIntlPlugin();
/** @type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: false,
};
module.exports = withNextIntl(nextConfig);
i18n.ts 설정 파일 추가
// i18n.ts
import { notFound } from 'next/navigation';
import { getRequestConfig } from 'next-intl/server';
// Can be imported from a shared config
const locales = ['en', 'ko', 'ja', 'zh'];
export default getRequestConfig(async ({ locale }) => {
// Validate that the incoming `locale` parameter is valid
if (!locales.includes(locale as any)) {
notFound();
}
return {
messages: (await import(`./messages/${locale}.json`)).default,
};
});
middleware.ts 추가
- Next JS 에서 middleware 파일은 요청(Request)과 응답(Response) 사이에 위치하여 다양한 작업을 수행한다. 이번 다국어 적용에선 라우팅을 제어하는 역할을 맡았다. middleware만 잘 설정하기만 하면 라이브러리 없이도 다국어를 구현할 수 있다.
import createMiddleware from 'next-intl/middleware';
export default createMiddleware({
locales: ['en', 'ko', 'ja', 'zh'],
defaultLocale: 'en',
});
export const config = {
// Match only internationalized pathnames
matcher: ['/((?!api|_next/static|_next/image|favicon.ico).*)'],
};
사용
CSR
export default function I18nTest = () => {
const t = useTranslations();
return <div>{t.test}<div>
}
SSR
export default async function Page({ params: { locale } }: DefaultPageProps) {
const t = await getTranslations({ locale });
return <div>{t.test}<div>
}