0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

nuxt-i18nとは

Posted at

🏆 ゴール 🏆

nuxt-i18nについて簡単な理解と使用方法について知る

使用方法については動くかの検証をしていないので本ドキュメントでは実装における大体知識が理解できれば良い

前提

Vue i18nの理解ができている

nuxt-i18nってなに?

nuxt-i18nは、Nuxt.js用のi18nのライブラリです。

Vue.js用のi18nライブラリであるVue i18nにいくつかの機能が追加され、Nuxt.jsでの使用に特化しています

vue i18n と nuxt-i18n どっち使えばいいの?

Vue i18nにいくつかの機能が追加され

のようにVue i18nをもとにNuxt.jsで作られているので、Nuxtであれば nuxt-i18n の選択肢で良さそう

言語ファイルを作成

ここでは、langディレクトリにJSON形式で英語と日本語の言語ファイルを作成します。

lang/ja.json
{
  "HELLO_WORLD": "こんにちは、世界"
}
lang/en.json
{
  "HELLO_WORLD": "Hello World"
}

nuxt-i18nの設定ファイルを作成

nuxt-i18nの設定をオブジェクトとして記述します。
nuxt.config.jsファイルに直接書いてもいいのですが、それなりに長いので別ファイルに切り出します。

nuxt-i18nには多くの設定項目がありますが、ここでは最小限のもののみを指定しています。

  • locales:使用する言語のリスト
    • code:URLなどに使用される識別子
    • iso:ISO形式の言語コード(詳細は後述)
    • file:言語ファイルのファイル名
  • defaultLocale:デフォルトの言語
  • lazy:言語ファイルを使用してレイジーロードをするか
  • langDir:言語ファイルのディレクトリ

ISO形式の言語コード

ISO形式の言語コードは、以下のいずれかの形式で指定する必要があります。

  • ISO 639-1のコード(言語コード)
    • jp
    • en
  • ISO 639-1のコード(言語コード)とISO 3166-1 alpha-2のコード(国名コード)をハイフンで結合
    • en-US
    • ja-JP

プロジェクトにモジュールを追加

nuxt.config.jsファイルのmodulesに、nuxt-i18nとオプションオブジェクトを配列として追加します。

nuxt.config.js
import i18n from './nuxt-i18n.config'

export default {
  modules: [
    ['nuxt-i18n', i18n]
  ]
}

ここでは、さきほど作成した設定ファイルをインポートしてオプションとして使用しています。
nuxt.config.jsファイルが肥大化するのを許容できるのであれば、以下のようにリテラルで書いてもいいでしょう。

nuxt.config.js
export default {
  modules: [
    ['nuxt-i18n', {
      locales: [
        {
          code: 'en',
          iso: 'en',
          file: 'en.json'
        },
        {
          code: 'ja',
          iso: 'ja',
          file: 'ja.json'
        }
      ],
      defaultLocale: 'en',
      lazy: true,
      langDir: 'lang/'
    }]
  ]
}

コンポーネントで使用

nuxt-i18nの言語ファイルで定義したリソースは、コンポーネント内では$t(キー)という形式で使用します。

pages/index.vue
<template>
  <div>
    <span>{{ $t('HELLO_WORLD') }}</span>
  </div>
</template>

こうすることで、表示中の言語に対応する文字列が表示されます。

引用

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?