i18n 国际化模块
本模块提供完整的国际化(i18n)支持,包括本地化配置、客户端和服务端的语言切换功能。
文件结构
src/lib/i18n/
├── index.ts # 模块入口,导出所有功能
├── config.ts # 本地化配置常量
├── client.ts # 客户端语言切换
└── server.ts # 服务端语言切换
支持的区域设置
支持 17 种语言,包括:
- 默认语言:
en(英语) - RTL 语言:
ar(阿拉伯语),he(希伯来语),fa(波斯语) - 其他语言:
tr,es,zh,ja,pt,it,de,nl,ko,ru,el,az
核心功能
配置常量 (config.ts)
| 常量 | 类型 | 说明 |
|---|---|---|
LOCALE_COOKIE | string | 存储语言偏好的 Cookie 名称 (NEXT_LOCALE) |
supportedLocales | string[] | 支持的语言列表 |
defaultLocale | string | 默认语言 (en) |
rtlLocales | string[] | 从右到左书写的语言 |
工具函数
isRtlLocale(locale: string): boolean
检查指定语言是否为 RTL(从右到左)语言。
getSupportedLocales(): string[]
获取所有支持的语言列表。
getDefaultLocale(): string
获取默认语言。
客户端操作 (client.ts)
setLocale(locale: string): void
设置用户语言偏好(客户端)。
- 更新 Cookie(有效期1年)
- 强制页面刷新以应用新语言
getLocaleClient(): string | null
从 Cookie 获取当前语言设置。
服务端操作 (server.ts)
setLocaleServer(locale: string): Promise<void>
设置用户语言偏好(服务端动作)。
- 验证语言是否受支持
- 更新 Cookie
- 如用户已登录,同步更新数据库
syncLocaleFromUser(userId: string): Promise<void>
用户登录时,将数据库中的语言偏好同步到 Cookie。
使用示例
// 客户端切换语言
import { setLocale } from '@/lib/i18n/client';
setLocale('zh');
// 服务端切换语言
import { setLocaleServer } from '@/lib/i18n/server';
await setLocaleServer('zh');
// 检查 RTL
import { isRtlLocale } from '@/lib/i18n/config';
const isRTL = isRtlLocale('ar'); // true
与 next-intl 集成
本模块与 next-intl 库配合使用,提供更完善的国际化支持。区域检测逻辑位于 src/i18n/request.ts。