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(),无需上下文。 - 客户端组件:使用
NextIntlClientProvider包裹。 - 为保持可维护性,建议按页面/组件对消息键进行命名空间划分。
- 使用
localePrefix: 'as-needed'避免为默认语言添加/en/前缀。