i18next は何をしますか?
概要
i18next は最も人気のある JavaScript i18n フレームワークです。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"><a href="/terms">利用規約</a>に同意する。</Trans>
</div>
)
}
{
"welcome": "おかえりなさい、{{name}}!",
"projects_one": "{{count}} 件のプロジェクトがあります",
"projects_other": "{{count}} 件のプロジェクトがあります"
}
ガイドライン
- 翻訳は機能ごとに名前空間に分割してください。すべてを読み込まないようにします。
- 複数形には
_one/_otherサフィックスを使用します。 - 埋め込み JSX を含む翻訳には
<Trans>を使用します。 - 言語検出の優先順位:ブラウザ → URL → Cookie → localStorage。
- SSR の場合:ハイドレーションの不一致を避けるために、サーバーから言語を渡します。