以下是一套完整的 Prompt,可以直接用于新网站的多语言实现:
Prompt: 为 Next.js 16 网站实现多语言国际化
请为我的 Next.js 16 网站实现完整的多语言国际化方案(中文、英文、日文、韩文)。
技术要求
- Next.js 16 App Router (output: “export” 静态导出)
- React + TypeScript
- 基于 URL 路径的多语言路由 (/, /en, /ja, /ko)
- 语言切换器组件
- 翻译文件集中管理
- 解决 hydration 闪烁问题
核心文件清单
1. 翻译配置 (lib/i18n.ts)
export type Locale = "zh" | "en" | "ja" | "ko";
export const locales: Locale[] = ["zh", "en", "ja", "ko"];
export const defaultLocale: Locale = "zh";
export const localeNames: Record<Locale, string> = {
zh: "中文",
en: "English",
ja: "日本語",
ko: "한국어",
};
export const translations = {
zh: { /* 所有中文翻译 */ },
en: { /* 所有英文翻译 */ },
ja: { /* 所有日文翻译 */ },
ko: { /* 所有韩文翻译 */ },
};
export function getTranslation(locale: Locale) {
return translations[locale] || translations.zh;
}
2. 路径工具 (lib/i18n-routing.ts)
export function getLocaleFromPath(pathname: string): Locale
export function addLocaleToPath(pathname: string, locale: Locale): string
export function switchLocalePath(pathname: string, newLocale: Locale): string
export function removeLocaleFromPath(pathname: string): string
3. 语言 Provider (components/LanguageProvider.tsx)
- 接收 locale prop,避免客户端检测
- 提供 useLocale hook
- 返回 { locale, setLocale, mounted }
4. 翻译 Hook (lib/useTranslation.ts)
export function useTranslation() {
const { locale } = useLocale();
const t = getTranslation(locale);
return { t, locale };
}
5. 语言切换器 (components/LanguageSwitcher.tsx)
- 使用 switchLocalePath 跳转
- 不刷新页面,直接跳转新语言路径
- 显示当前语言
6. 导航栏更新
const { t, locale } = useTranslation();
const getLocalizedHref = (path: string) => addLocaleToPath(path, locale);
// 所有 Link 使用 getLocalizedHref
7. 页面路由结构
app/
├── page.tsx # 根路径,默认中文
├── [lang]/page.tsx # 多语言首页
├── features/page.tsx # 根路径功能页
├── [lang]/features/page.tsx # 多语言功能页
8. 页面组件模板
// app/[lang]/page.tsx
export default async function LangPage({ params }: { params: Promise<{ lang: string }> }) {
const { lang } = await params;
return (
<LanguageProvider locale={lang as Locale}>
<PageContent lang={lang} />
</LanguageProvider>
);
}
关键原则
- 避免闪烁:语言通过 props 从服务端传入,不依赖客户端 localStorage 初始化
- 路径路由:/en 直接渲染英文,不使用重定向
- 导航保持:切换语言时保持在当前页面路径
- SEO 友好:每个语言有独立 URL,支持静态导出
翻译文件结构示例
// lib/i18n.ts
export const translations = {
zh: {
nav: { home: "首页", features: "功能", pricing: "价格" },
hero: { title: "AI 自动化平台", subtitle: "提升效率" },
// ... 其他翻译
},
en: {
nav: { home: "Home", features: "Features", pricing: "Pricing" },
hero: { title: "AI Automation Platform", subtitle: "Boost Efficiency" },
// ... 其他翻译
},
// ja, ko 同理
};
使用方式
在组件中使用:
const { t } = useTranslation();
// t.nav.home, t.hero.title
请按照以上架构为我实现完整的多语言方案,确保:
- 无闪烁
- 语言切换流畅
- 所有页面支持多语言
- 导航链接正确
- TDK 正确切换
使用这个 Prompt,我会一次性为你完成所有多语言实现。