next-intl
概述
next-intl 是 Next.js App Router 領先的 i18n 函式庫。它處理語言環境路由、訊息翻譯、日期/數字格式化,並同時支援伺服器端與客戶端元件。採用 ICU 訊息語法處理複數與變數。
操作步驟
步驟 1:設定
npm install next-intl
// i18n/request.ts — 語言環境偵測
import { getRequestConfig } from 'next-intl/server'
export default getRequestConfig(async ({ requestLocale }) => {
const locale = await requestLocale || 'en'
return {
locale,
messages: (await import(`../messages/${locale}.json`)).default,
}
})
// messages/en.json
{
"HomePage": {
"title": "Welcome to {appName}",
"description": "The best tool for {count, plural, one {# team} other {# teams}}",
"cta": "Get Started"
},
"Dashboard": {
"greeting": "Hello, {name}",
"lastLogin": "Last login: {date, date, medium}"
}
}
// messages/de.json
{
"HomePage": {
"title": "Willkommen bei {appName}",
"description": "Das beste Tool für {count, plural, one {# Team} other {# Teams}}",
"cta": "Jetzt starten"
}
}
步驟 2:伺服器端元件
// app/[locale]/page.tsx — 翻譯後的伺服器端元件
import { useTranslations } from 'next-intl'
export default function HomePage() {
const t = useTranslations('HomePage')
return (
<main>
<h1>{t('title', { appName: 'MyApp' })}</h1>
<p>{t('description', { count: 5000 })}</p>
<a href="/signup">{t('cta')}</a>
</main>
)
}
步驟 3:中介軟體路由
// middleware.ts — 語言環境路由
import createMiddleware from 'next-intl/middleware'
export default createMiddleware({
locales: ['en', 'de', 'fr', 'ja'],
defaultLocale: 'en',
localePrefix: 'as-needed', // /de/about 但 /about (針對 en)
})
export const config = { matcher: ['/((?!api|_next|.*\\..*).*)'] }
準則
- ICU 訊息語法:使用
{count, plural, one {# item} other {# items}}來處理複數形式。 - 伺服器端元件:直接使用
useTranslations(),無需 context。 - 客戶端元件:使用
NextIntlClientProvider包裹。 - 根據頁面/元件命名訊息鍵值,以利於維護。
- 使用
localePrefix: 'as-needed'可為預設語言環境省略/en/前綴。