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を記載する