第六章:Next.js 进阶
国际化 (i18n)
1. 什么是国际化 (i18n)?
国际化(Internationalization,简称 i18n)是指设计和开发应用程序,使其能够轻松适应不同语言和地区的需求。在 Next.js 中,国际化功能允许你为不同语言的用户提供本地化的内容,包括文本、日期格式、货币符号等。
2. Next.js 内置的 i18n 支持
Next.js 提供了开箱即用的国际化支持,通过配置 next.config.js 文件可以轻松启用多语言功能。以下是关键配置项:
// next.config.js
module.exports = {
i18n: {
locales: ['en', 'fr', 'de'], // 支持的语言列表
defaultLocale: 'en', // 默认语言
},
}
3. 实现多语言路由
Next.js 的国际化功能会自动为每种语言生成对应的路由。例如:
/about(默认英语)/fr/about(法语)/de/about(德语)
你可以使用 next/router 或 next/link 来切换语言:
import { useRouter } from 'next/router';
function LanguageSwitcher() {
const router = useRouter();
return (
<select
value={router.locale}
onChange={(e) => router.push(router.pathname, router.asPath, { locale: e.target.value })}
>
<option value="en">English</option>
<option value="fr">Français</option>
<option value="de">Deutsch</option>
</select>
);
}
4. 管理多语言内容
通常我们会将不同语言的文本内容存储在 JSON 文件中,例如:
// locales/en/common.json
{
"title": "Welcome to my app",
"description": "This is a demo application"
}
// locales/fr/common.json
{
"title": "Bienvenue sur mon application",
"description": "Ceci est une application de démonstration"
}
然后在组件中使用:
import { useRouter } from 'next/router';
import translations from '../locales';
function HomePage() {
const { locale } = useRouter();
const t = translations[locale];
return (
<div>
<h1>{t.title}</h1>
<p>{t.description}</p>
</div>
);
}
5. 高级国际化功能
Next.js 还支持更高级的国际化功能:
- 自动语言检测:根据用户浏览器设置自动选择语言
- 域名国际化:不同语言使用不同域名(如
example.com和example.fr) - 动态导入翻译文件:按需加载语言包减少初始加载时间
- 格式化日期和数字:使用
IntlAPI 根据地区格式化内容
6. 最佳实践
- 将所有可翻译文本集中管理
- 为翻译人员提供上下文注释
- 考虑文本长度变化对布局的影响
- 测试RTL(从右到左)语言支持
- 使用专业的翻译管理系统(如i18next、LinguiJS等)
通过合理使用Next.js的国际化功能,你可以轻松构建支持多语言的全球性应用程序。
