Skip to content

Instantly share code, notes, and snippets.

@matsumana07384
Last active March 17, 2019 14:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matsumana07384/c346967544b875af754bcaf90c053d2a to your computer and use it in GitHub Desktop.
Save matsumana07384/c346967544b875af754bcaf90c053d2a to your computer and use it in GitHub Desktop.
wip

Nuxt.jsで多言語化デビューしよう!

2019/03/25に開催のサポーターズCoLabイベントの説明資料です。

前提

  • 動作確認端末
    • Mac OS X 10.14.3
  • インストールされているライブラリ

Nuxt.jsをインストール

公式ページのインストール手順に沿って行っていきます。 今回は簡単に行うため、npxを使用します。

npm(Node Package Manager)のバージョンを確認します

npm -v 

5.2.0 以上が表示されればOKです。

Nuxtプロジェクトの作成

プロジェクトを作ります。

npx create-nuxt-app ColabApp

ColabAppはフォルダ名になるため、自分が管理しやすい名前を設定してください。

サイト名の入力

()の中身から変更しない場合はそのままEnterキーを押下しましょう。

? Project name (ColabApp)

サイト名の詳細の入力

()の中身から変更しない場合はそのままEnterキーを押下しましょう。

? Project description (My grand Nuxt.js project)

サーバーフレームワークの選択

今回はNuxt.jsを使用するため、Noneを選択し、Enterキーを押下します。

? Use a custom server framework (Use arrow keys)
❯ none
  express
  koa
  adonis
  hapi
  feathers
  micro
(Move up and down to reveal more choices)

追加機能の選択

複数選択することも可能ですが、今回は Progressive Web App (PWA) Supportのみを選択します。

? Choose features to install (Press <space> to select, <a> to
 toggle all, <i> to invert selection)
❯◯ Progressive Web App (PWA) Support
 ◯ Linter / Formatter
 ◯ Prettier
 ◯ Axios

それぞれの機能をざっくり説明すると下記のようになります。

  • Progressive Web App (PWA) Support

  • Linter / Formatter

    • コードの構文チェックを行うツール。JavaScriptだとESlintJSLintが有名だと思います。
  • Prettier

    • ソースコードを整形するツール。規定に従って強制的にソースコードを整形するため、チーム開発で導入すると恩恵を受けられると思います。
  • Axios

    • HTTP通信ができるJavaScriptライブラリ。JSONの取得に利用されることが多いと思います。

UIフレームワークの選択

このときにNoneを選んでもあとから追加することは可能です。 今回は個人的に気になっているblumaを選択します。

? Use a custom UI framework
  none
  bootstrap
  vuetify
❯ bulma
  tailwind
  element-ui
  buefy

それぞれの詳細については公式ページをご確認ください。

テスティングフレームワークの選択

今回はテストまでは行わないため、Noneを選択します。 (品質を保証する上でテストは大切だと思います!!)

? Use a custom test framework (Use arrow keys)
❯ none
  jest
  ava

それぞれの詳細については公式ページをご確認ください。

Nuxtのモードの選択

今回はUniversalを選択します。

? Choose rendering mode
❯ Universal
  Single Page App

それぞれの意味は下記の通りです。

  • Universal

    • クライアントもサーバーサイドもNuxtで開発をする際に使用
  • Single Page App

    • クライアントサイドのみの開発をする際に使用

著者の名前を選択

PCにGithubの設定を行っていると自動的にGithubのアカウントが表示されます。 今回は特に変更する理由ないため、そのままEnterキーを押下します。

? Author name (yourname)

最後にパッケージマネージャーを選択します。 今回はnpmを選択します。

? Choose a package manager (Use arrow keys)
❯ npm
  yarn

それぞれの詳細については公式ページをご確認ください。

上記までを設定するとインストールが始まります。 環境にもよるかと思いますが、インストールが完了するかと思います。

Nuxt.js を起動

インストールが完了すると、下記がターミナル上に表示されているはずです。

To get started:

	cd ColabApp
	npm run dev

  To build & start for production:

	cd ColabApp
	npm run build
	npm start

ディレクトリの移動

先程 npx create-nuxt-app で設定したディレクトリに移動します。

cd ColabApp

Webページを起動

npmで起動します。

npm run dev

下記の画面が表示されれば、無事に起動しています。 ブラウザから http://localhost:3000 にアクセスしてみましょう。

   ╭──────────────────────────────╮
   │                                             │
   │   Nuxt.js v2.4.5                            │
   │   Running in development mode (universal)   │
   │   Memory usage: 164 MB (RSS: 287 MB)        │
   │                                             │
   │   Listening on: http://localhost:3000       │
   │                                             │
   ╰──────────────────────────────╯

i18nのインストール

公式ドキュメントに沿って進めていきます。 ライブラリのインストールを行うため、Ctrl + Cのキーを押下し、ローカル環境を止めます。

vue-i18nをインストール

npm install vue-i18n --save

インストールに成功すると、下記が表示されます。

+ vue-i18n@8.9.0
added 1 package from 1 contributor and audited 13865 packages in 19.139s
found 0 vulnerabilities

多言語化の設定

多言語化ができるように各ファイルを作成や修正を行います。 今回はターミナルでの操作を基本として進めていきます。

翻訳ファイルの作成

管理用フォルダを作成

フォルダ名はなんでもOKですが、今回は ‌locales にします。

mkdir locales

翻訳ファイルの作成

作ったlocalesフォルダに英語と日本語のファイルを作ります。

touch locales/en.json
touch locales/ja.json

翻訳ファイルの追記(英語)

英語の翻訳テキストを記述します。

{
  "links": {
    "home": "Home",
    "about": "About",
    "en": "English",
    "ja": "Japanese"
  },
  "home": {
    "title": "Hello,World!",
    "introduction": "This is an introduction in English."
  }
}

`

翻訳ファイルの追記(日本語)

日本語の翻訳テキストを記述します。

{
  "links": {
    "home": "ほーむ",
    "about": "あばうと",
    "en": "えいご",
    "ja": "にほんご"
  },
  "home": {
    "title": "やぁ、世界!",
    "introduction": "このページは日本語で設定されています"
  }
}

英語と日本語のJSON構造が合っていないと、Webページ上で翻訳がきちんと表示されないため、気をつけましょう。

i18nライブラリの設定

i18n用のファイルを作成

pluginsフォルダにファイルを作成します。

touch plugins/i18n.js

plugins/i18n.jsの追記

plugins/i18n.jsに記述します。

import Vue from 'vue'
import VueI18n from 'vue-i18n'

Vue.use(VueI18n)

export default ({ app, store }) => {
  app.i18n = new VueI18n({
    locale: store.state.locale,
    fallbackLocale: 'ja',
    messages: {
      'ja': require('~/locales/ja.json'),
      'en': require('~/locales/en.json')
    }
  })

  app.i18n.path = (link) => {
    if (app.i18n.locale === app.i18n.fallbackLocale) {
      return `/${link}`
    }
    return `/${app.i18n.locale}/${link}`
  }
}

HTTPリクエスト毎の設定

HTTPリクエスト毎に現在の言語を設定します。

フォルダの作成

middlewareフォルダにファイルを作成します。

touch middleware/i18n.js

middleware/i18n.jsの追記

middleware/i18n.jsに記述します。

export default function ({ isHMR, app, store, route, params, error, redirect }) {
  const defaultLocale = app.i18n.fallbackLocale
  // If middleware is called from hot module replacement, ignore it
  if (isHMR) return
  // Get locale from params
  const locale = params.lang || defaultLocale
  if (store.state.locales.indexOf(locale) === -1) {
    return error({ message: 'This page could not be found.', statusCode: 404 })
  }
  // Set locale
  store.commit('SET_LANG', locale)
  app.i18n.locale = store.state.locale
  // If route is /<defaultLocale>/... -> redirect to /...
  if (locale === defaultLocale && route.fullPath.indexOf('/' + defaultLocale) === 0) {
    const toReplace = '^/' + defaultLocale + (route.fullPath.indexOf('/' + defaultLocale + '/') === 0 ? '/' : '')
    const re = new RegExp(toReplace)
    return redirect(
      route.fullPath.replace(re, '/')
    )
  }
}

ストアに設定

ストアに言語設定を行い、各ページで利用できるように設定します。

ファイルの作成

storeフォルダにファイルを作成します。

touch store/index.js

store/index.jsの追記

store/index.jsに記述します。

export const state = () => ({
    locales: ['en', 'ja'],
    locale: 'ja'
  })
  
export const mutations = {
  SET_LANG(state, locale) {
    if (state.locales.indexOf(locale) !== -1) {
      state.locale = locale
    }
  }
}

設定ファイルへの反映

nuxt.config.js にプラグインとライブラリの設定をします。

nuxt.config.jsの追記

下記を記述します。 nuxt.config.jsに記述します。


  plugins: [
    '~/plugins/i18n.js' //追加
  ],
//ここから以下を追加
  vendor: [
    'vue-i18n'  
  ],
  router: {
    middleware: 'i18n'
  },
  generate: {
    routes: ['/', '/about', '/en', '/en/about']
  } ,

以上で多言語化の設定は完了です🎉

Vueファイルの設定

Nuxt.jsでは pages以下のディレクトリ構造がそのままURLのパス(http://domain/`‌ファイル名`)に対応します。

言語パスのディレクトリの作成

mkdir pages/_lang

_をつけるとURLのパスから除外されます。 今回は_langの部分に言語名を埋め込むために設定します。

index.vueをコピー

index.vueファイルを_lang以下にコピーします。

cp pages/index.vue pages/_lang/index.vue

この項目は必須ではありませんが、作業を楽にするために行っています。

Webページの初期ファイルを編集

http://localhost:3000/ の参照ファイルを変更するため、pages/index.vue に記述します。

<script>
import Index from '~/pages/_lang/index'
export default Index
</script>

これで http://localhost:3000/ を開いたときにpages/_lang/index.vue が表示されるようなります。

これで基本設定が完了しました!

ローカルホストを起動

ここからはローカルホストを起動しながら進めていきます。

npm run dev

pages/_lang/index.vueの編集

翻訳テキストが表示できるようにするため、該当箇所を編集します。 //が編集前の内容です。

<template>
…
  <h1 class="title">
    {{ $t('home.title') }} //ColabApp
  </h1>
  <h2 class="subtitle">
    {{ $t('home.introduction') }} //My grand Nuxt.js project
  </h2>
…
</template>

AppHeader.vueを作成

言語切替を行う用のcomponents/AppHeader.vueを作成します。

ファイルを作成

touch components/AppHeader.vue

components/AppHeader.vueの編集

components/AppHeader.vueに記述します。

<template>
  <header class="Header">
    <div class="links">
      <NuxtLink :to="$i18n.path('')">
        {{ $t('links.home') }}
      </NuxtLink>
      <NuxtLink v-if="$i18n.locale === 'ja'" :to="`/en` + $route.fullPath">
        {{ $t('links.en') }}
      </NuxtLink>
      <NuxtLink v-else :to="$route.fullPath.replace(/^\/[^\/]+/, '')">
        {{ $t('links.ja') }}
      </NuxtLink>
    </div>
  </header>
</template>
<script>
export default {
    
}
</script>
<style scoped>
</style>

今回は、日本語表示のときは英語の切り替え、英語表示のときは日本語切り替えが表示される分岐処理を追加しています。

レイアウトファイルの編集

先程作った‌components/AppHeader.vueが常に表示されるように設定します。

layouts/default.vueを編集

layouts/default.vueに記述します。

<template>
  <div>
    <AppHeader></AppHeader>/*追加*/
    <nuxt />
  </div>
</template>

//ここから
<script>
import AppHeader from '@/components/AppHeader.vue'

export default {
  components: {
    AppHeader
  }
}
</script>
//ここまでを追加
<style>
</style>

layouts/default.vueでは、全ページのレイアウトを設定しています。 今回は、作成したコンポーネントAppHeader.vueをインポートし、ヘッダーとして表示できるように設定しています。

ページの確認

http://localhost:3000を確認しましょう

えいごのリンクテキストhttp://localhost:3000/enをクリックすると、設定した翻訳テキストが表示されます。

ここまでお付き合い頂き、ありがとうございました!

追加演習

pages/_lang/about.vue ページを追加して、翻訳テキストを表示してみましょう

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment