LoginSignup
6
4

More than 5 years have passed since last update.

nuxt.jsでi18nするまで

Posted at

なんだかまとまっている情報がどこにあるんだかわからんなぁ・・・と少々路頭に迷ったのでまとめておく。

やりたいこと

  • nuxt.jsのi18nをしたい
  • 定義ファイルはyamlで書きたい

やり方にたどり着くまで

結局実施した変更

nuxt.config.jsに以下を追記

modulesセクション

 modules: [
    // Doc: https://axios.nuxtjs.org/usage
    '@nuxtjs/axios',
    // Doc:https://github.com/nuxt-community/modules/tree/master/packages/bulma
    '@nuxtjs/bulma',
    '@nuxtjs/pwa',
    // 以下追記
    [
      'nuxt-i18n',
      {
        locales: [{ code: 'ja', iso: 'ja_JP' }, { code: 'en', iso: 'en-US' }],
        defaultLocale: 'ja',
        vueI18n: {
          fallbackLocale: 'ja',
        },
        vueI18nLoader: true,
      },
    ],
  ],

buildセクション

  build: {
    postcss: {
      preset: {
        features: {
          customProperties: false,
        },
      },
    },
    /*
     ** You can extend webpack config here
     */
    extend(config, ctx) {
      // この部分を追記
      config.module.rules.push({
        resourceQuery: /blockType=i18n/,
        type: 'javascript/auto',
        loader: ['@kazupon/vue-i18n-loader', 'yaml-loader'],
      })
      ...
    },
  },

変換用のファイルを設置

自分の場合は、 @/locales/ja.yaml , @/locales/en.yaml を置いてそこに以下を追記

ja.yaml

ja:
  hello: 'こんにちは世界'

en.yaml

en:
  hello: 'Hello World'

ファイル内でyamlをインポートしつつにmsgid相当を記載

とりあえず普通にsrcしたけど、多分layoutに書くとか、moduleでimportするとかでも行ける模様。

ちなみに @ は忘れがちですが srcDir へのエイリアスですね。

<i18n src="@/locales/ja.yaml"></i18n>
<i18n src="@/locales/en.yaml"></i18n>

<template>
  <section class="section">
    {{ $t('hello') }} <-- こんにちは世界
  </section>
</template>

ちなみにこのtemplateではbulmaを使ってますが、まぁそこはあまり大事ではないので大丈夫かなと。

以上。

6
4
2

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
6
4