51
43

More than 3 years have passed since last update.

NuxtJSの国際化にはnuxt-i18nを使おう

Last updated at Posted at 2018-10-15

現在日本語の記事ではNuxtJS上でvue-i18nを使って国際化を行う方法のみ説明されています。
しかしそれらは1年以上前のものだったりして少々古く、2018年10月現在ではnuxt-i18nというnuxt用にvue-i18nを拡張したプラグインが開発されています。
なので今回はこのnuxt-i18nを使って国際化を行ってみたいと思います。

前準備: Nuxtプロジェクトの作成

以下設定でNuxtプロジェクトを作成します(Project Name以外デフォルト)

$ create-nuxt-app
> Generating Nuxt.js project in /Users/wildmouse/develop/practice
? Project name nuxt-with-i18n
? Project description My mind-blowing Nuxt.js project
? Use a custom server framework none
? Use a custom UI framework none
? Choose rendering mode Universal
? Use axios module no
? Use eslint no
? Use prettier no
? Author name (wildmouse)
? Choose a package manager npm

プロジェクトの作成が完了したらcd nuxt-with-i18nで移動し、準備完了。

nuxt-i18nの追加

次にnuxt-i18nのインストールを実行。

$ npm install --save nuxt-i18n

でインストールが完了します。

nuxt-i18nの設定

インストールが完了したらnuxt.config.jsに設定を追加していきます。

nuxt.config.js
modules: [
  [
    'nuxt-i18n',
    {
      locales: [
        { code: 'ja', iso: 'ja-JP' },
        { code: 'en', iso: 'en-US' },
      ],
      defaultLocale: 'ja',
      vueI18n: {
        fallbackLocale: 'ja',
      },
      vueI18nLoader: true
    }
  ]
],

国際化させる文章を登録

プロジェクトでの設定が完了したら、次に個々のページで対応化させたい単語・文章の登録をします。
各vueファイルの<template>上部に<i18n>タグを追加し、JSON形式で記述することで国際化が可能になります。

index.vue
<i18n>
  {
    "ja": {
      "hello": "こんにちは世界"
    },
    "en": {
      "hello": "Hello World"
    },
  }
</i18n>

国際化した文言を表示させる

文言が登録できればあとはtemplate側で使用すればOK。

index.vue
<template>
  <div>
    {{ $t('hello') }}
  </div>
</template>

npm run devを叩いて http://localhost:3000 にアクセスすると、こんにちは世界と表示されているのが確認できるはずです。

参考

https://github.com/kazupon/vue-i18n-loader
http://kazupon.github.io/vue-i18n/

51
43
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
51
43