name: 国际化-i18n description: 使用i18next、gettext或Intl API实现多语言支持,包括翻译工作流和RTL支持。用于构建多语言应用、处理日期/货币格式化或支持从右到左语言。
国际化 (i18n)
实现多语言支持,包括适当的翻译管理和格式化。
i18next 设置 (React)
import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
import LanguageDetector from 'i18next-browser-languagedetector';
i18n
.use(LanguageDetector)
.use(initReactI18next)
.init({
fallbackLng: 'en',
interpolation: { escapeValue: false },
resources: {
en: { translation: { welcome: 'Welcome, {{name}}!' } },
es: { translation: { welcome: '¡Bienvenido, {{name}}!' } },
zh: { translation: { welcome: '欢迎, {{name}}!' } } // 添加中文翻译
}
});
// 用法
const { t } = useTranslation();
<h1>{t('welcome', { name: 'John' })}</h1>
复数化
// 翻译文件
{
"items": "{{count}} 项",
"items_plural": "{{count}} 项",
"items_zero": "无项"
}
// 用法
t('items', { count: 0 }) // "无项"
t('items', { count: 1 }) // "1 项"
t('items', { count: 5 }) // "5 项"
日期/数字格式化
// 日期
new Intl.DateTimeFormat('de-DE', {
dateStyle: 'long',
timeStyle: 'short'
}).format(new Date());
// 数字
new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD'
}).format(1234.56); // "$1,234.56"
// 相对时间
new Intl.RelativeTimeFormat('en', { numeric: 'auto' })
.format(-1, 'day'); // "yesterday"
RTL 支持
/* 使用逻辑属性 */
.container {
margin-inline-start: 1rem; /* 在LTR中为margin-left,在RTL中为margin-right */
padding-inline-end: 1rem;
}
/* 方向属性 */
html[dir="rtl"] .icon {
transform: scaleX(-1);
}
额外框架
参见 references/frameworks.md 获取:
- React-Intl (Format.js) 完整实现
- Python gettext 与 Flask/Babel
- RTL 语言支持模式
- ICU 消息格式示例
最佳实践
- 提取所有面向用户的字符串
- 使用 ICU 消息格式进行复杂翻译
- 使用伪本地化测试
- 从一开始就支持 RTL
- 永远不要连接翻译字符串
- 生产环境使用专业翻译人员