[特殊字符] next-intl 服务端 i18n getTranslations 教程
next-intl
是为 Next.js 提供国际化(i18n)支持的强大库,getTranslations
是它在 服务器端加载翻译文本 时的重要函数,适用于 App Router 场景(如 app/
目录下的页面、layout、server component)。
✅ 安装 next-intl
如果你还没安装:
npm install next-intl
🌍 项目结构建议
.
├── app
│ ├── [locale] # 动态路由处理多语言
│ │ ├── page.tsx
│ │ ├── layout.tsx
├── messages
│ ├── en.json
│ ├── zh.json
├── middleware.ts
📦 创建多语言 JSON 文件(如 messages/en.json
)
jsonCopyEdit
{"home": {"title": "Welcome to the site!","description": "This is a demo page."}
}
🛠 配置 middleware.ts
tsCopyEdit
import createMiddleware from 'next-intl/middleware';export default createMiddleware({locales: ['en', 'zh'],defaultLocale: 'en'
});export const config = {matcher: ['/', '/(en|zh)/:path*']
};
📚 使用 getTranslations
(核心部分)
👇 示例:app/[locale]/page.tsx
tsxCopyEdit
import { getTranslations } from 'next-intl/server';export default async function HomePage() {const t = await getTranslations('home'); // 读取 "home" 命名空间return (<div><h1>{t('title')}</h1><p>{t('description')}</p></div>);
}
✅ getTranslations
是 服务器端函数,适用于 Server Component
中(也就是不能用于 use client
的组件中)。
📌 getTranslations
的参数说明
tsCopyEdit
const t = await getTranslations(namespace?: string);
namespace
(可选):对应 JSON 中的顶层键,如home
。- 返回的
t
是一个类似函数的对象,可用于t('key')
获取翻译值。
如果你的翻译结构是这样的:
jsonCopyEdit
{"hello": "你好","user": {"greeting": "你好,{name}!"}
}
你可以这样用:
tsCopyEdit
const t = await getTranslations();
t('hello'); // "你好"
t('user.greeting', { name: '小明' }); // "你好,小明!"
⚠ 注意事项
getTranslations
只能在 服务器组件、layout.tsx 或 page.tsx 中使用。- 对于客户端组件,使用
useTranslations()
(配合use client
)代替。 - 多语言的 JSON 文件应放在统一的
messages/
目录,并按语言命名。
🎯 小技巧:动态传参
tsCopyEdit
const t = await getTranslations();
const name = 'David';
t('user.greeting', { name }); // "Hello, David!"
💡 配合 layout 使用
tsxCopyEdit
// app/[locale]/layout.tsx
import { getTranslations } from 'next-intl/server';export default async function LocaleLayout({ children }: { children: React.ReactNode }) {const t = await getTranslations('layout');return (<><header>{t('title')}</header>{children}</>);
}
🧪 适用于的场景
- SEO 友好的 SSR 多语言页面
- 服务端渲染组件中需要使用国际化
- App Router 模式下使用
layout.tsx
、page.tsx
或server component