LoginSignup
10
6

More than 5 years have passed since last update.

i18next の使用例

Last updated at Posted at 2017-02-08

国際化はそんなに理解が難しい処理ではないと思うんですが、i18nextの使い方を調べるのに思ってた以上に手間取ったので、基本的な使い方をメモとして残しておきます。

i18next

i18nextオブジェクトの初期化

initメソッドを呼び出してi18nextオブジェクトを初期化する必要がある。

翻訳データをこの時点で準備できるなら、resources パラメータに渡すことができます。ドキュメントの Getting started がいいサンプルになっています。

あとから言語を切り替えるとき

changeLanguage メソッドを使います。

あとから翻訳データを追加するとき

addResources メソッドを使います。

翻訳データの取得

tメソッドを使います。

使用例

import i18n from 'i18next';

i18n.
  init(
    {
      fallbackLng: 'en',
      resources: {}
    }
  );

i18n.addResources('en', 'translation', {hoge: 'foo', moge: 'bar'}); // 'translation' はデフォルトのネームスペース。initの引数でデフォルトのネームスペースを変えることもできる
i18n.addResources('ja', 'translation', {hoge: 'ほげ', moge: 'もげ'});

console.log(i18n.t('hoge'));
// => foo

i18n.changeLanguage('ja');

console.log(i18n.t('hoge'));
// => ほげ

react-i18next などの、i18nextを利用したライブラリを使うときでも、翻訳データのセットや言語の切り替えは、この仕組を使うことができます。

その他のAPIの説明は、API document から確認できます。

以上です。

10
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
6