国际化 (i18n)
使用 next-intl 为您的应用添加多语言支持。
NextSaas 基于 next-intl 构建,提供完整的国际化支持。它预配置了英语 (en) 和中文 (zh-CN)。
翻译文件
翻译文件存储在 messages 目录中。为了便于维护,我们将消息组织成独立的 JSON 文件(例如 common, auth, dashboard)。
messages/
├── en/
│ ├── common.json
│ ├── auth.json
│ └── ...
└── zh-CN/
├── common.json
├── auth.json
└── ...在 src/i18n/request.ts 中,我们动态加载并合并这些文件:
// src/i18n/request.ts
export default getRequestConfig(async ({ requestLocale }) => {
// ...
return {
messages: {
...(await import(`../../messages/${locale}/common.json`)).default,
...(await import(`../../messages/${locale}/sign.json`)).default,
// ...
},
};
});添加新语言
要添加新语言(例如日语 ja):
-
创建翻译文件: 创建一个
messages/ja目录,并从en复制 JSON 文件。翻译内容。 -
更新路由: 编辑
src/i18n/routing.ts以包含新的语言环境。export const locales = [defaultLocale, "zh-CN", "ja"]; -
更新中间件:
src/middleware.ts中的中间件会自动根据routing.ts处理路由。
使用翻译
在组件中
使用 useTranslations钩子访问消息。
import { useTranslations } from "next-intl";
export default function Welcome() {
const t = useTranslations("Common"); // "Common" 对应合并消息中的键
return <h1>{t("welcome")}</h1>;
}在服务端组件中
对于异步服务端组件,您可以使用 getTranslations。
import { getTranslations } from "next-intl/server";
export default async function Page() {
const t = await getTranslations("Metadata");
return {
title: t("title"),
};
}