i18next
概述
i18next 是最流行的 JS 国际化框架,支持 React、Vue、Angular、Node.js。特性包括命名空间拆分、懒加载、复数处理、插值、上下文以及用于远程翻译的后端插件。
教程
步骤 1:React 配置
import i18n from 'i18next'
import { initReactI18next } from 'react-i18next'
import HttpBackend from 'i18next-http-backend'
import LanguageDetector from 'i18next-browser-languagedetector'
i18n.use(HttpBackend).use(LanguageDetector).use(initReactI18next).init({
fallbackLng: 'en',
supportedLngs: ['en', 'de', 'fr', 'ja'],
ns: ['common', 'dashboard'],
defaultNS: 'common',
backend: { loadPath: '/locales/{{lng}}/{{ns}}.json' },
})
步骤 2:使用方法
import { useTranslation, Trans } from 'react-i18next'
function Dashboard() {
const { t } = useTranslation('dashboard')
return (
<div>
<h1>{t('welcome', { name: 'Alice' })}</h1>
<p>{t('projects', { count: 5 })}</p>
<Trans i18nKey="terms">Agree to <a href="/terms">Terms</a>.</Trans>
</div>
)
}
{
"welcome": "Welcome back, {{name}}!",
"projects_one": "You have {{count}} project",
"projects_other": "You have {{count}} projects"
}
指南
- 按功能将翻译拆分到不同的命名空间中——不要一次性加载全部。
- 使用
_one/_other后缀处理复数形式。 - 对于含有嵌入式 JSX 的翻译,使用
<Trans>组件。 - 语言检测顺序:浏览器 → URL → Cookie → localStorage。
- 对于 SSR(服务端渲染):从服务端传递语言参数以避免水合不匹配。