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):從伺服器傳遞語言參數,以避免水合(Hydration)不一致。