Next.js 10 で国際化対応したルーティングはできるようになった
今度はそのlocale
をつかってページの翻訳をしたい
Next.jsのリポジトリにnext-translateを使ったサンプルコードがあるので参考にする
https://github.com/vercel/next.js/tree/canary/examples/with-next-translate
Next-translate
Next-translateは、Next.jsページを翻訳するためのツール
まず注意しなければならないのは、/pages
ディレクトリを操作してページを作成する代わりに、任意のビルド前フォルダ(デフォルト/pages_
)を生成し、そこで実装することになる
そして、ビルドによって/pages
にファイルができるため、/pages
フォルダは.gitignore
に記載する必要がある
これをbuild step
と呼ぶとのこと(他の方法もあるみたいだが、別の日に確認する)
手順
next-translateのインストール
$ npm i -D next-translate
package.jsonを修正する
"scripts": { "dev": "next-translate && next dev", "build": "next-translate && next build", "start": "next start" }
{ "locales": ["en", "ja"], "defaultLocale": "en", "currentPagesDir": "src/pages_", "finalPagesDir": "src/pages", "localesPath": "src/static/locales", "pages": { "*": ["common"] "/": ["home"] } }
/locales
にjsonファイルを用意する
. ├── en │ ├── common.json │ └── home.json └── ja ├── common.json └── home.json
common.json
{ "title": "Hello world", "variable-example": "Using a variable {{count}}" }
next.config.jsの修正
const { locales, defaultLocale } = require('./i18n.json') module.exports = { i18n: { locales, defaultLocale }, }
ページを作成する
pages_/example.js
import useTranslation from 'next-translate/useTranslation' // ... const { t, lang } = useTranslation() const example = t('common:variable-example', { count: 42 }) // ... return <div>{example}</div>
.gitignoreに/pages
を記載する