こちらのページを参考にしました。
Step-by-step: How to Internationalize your NextJS App with Next-Translate
次のようなページを作成します。
日本語、英語、フランス語、エスペラント語に対応します。
プロジェクトの作成
npx create-next-app@latest proj01
フォルダー構造は次のようになります。
$ tree proj01 -I node_modules
proj01
├── README.md
├── next.config.js
├── package.json
├── pages
│ ├── _app.js
│ ├── api
│ │ └── hello.js
│ └── index.js
├── public
│ ├── favicon.ico
│ └── vercel.svg
├── styles
│ ├── Home.module.css
│ └── globals.css
└── yarn.lock
サーバーの実行
cd proj01
yarn dev
http://localhost:3000
にアクセスして、サーバーが動いていることを確認
多言語化
ライブラリーのインストール
npm install next-translate
次のファイルを差し替え
pages/index.js
next.config.js
pages/index.js
import useTranslation from 'next-translate/useTranslation';
import Head from 'next/head';
import Link from 'next/link';
import styles from '../styles/Home.module.css';
export default function Home() {
const { t } = useTranslation('common');
return (
<div className={styles.container}>
<Head>
<title>{t('metaTitle')}</title>
</Head>
<main className={styles.main}>
<h2 className={styles.title}>{t('title')}</h2>
<p className={styles.description}>{t('description')}</p>
<Link href="/" locale="fr">
<p><button>Français</button></p>
</Link>
<Link href="/" locale="ja">
<p><button>日本語</button></p>
</Link>
<Link href="/" locale="en">
<p><button>English</button></p>
</Link>
<Link href="/" locale="eo">
<p><button>Esperanto</button></p>
</Link>
</main>
</div>
);
}
next.config.js
/** @type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: true,
}
module.exports = nextConfig
const nextTranslate = require('next-translate')
module.exports = nextTranslate({
reactStrictMode: true,
})
次のファイルを作成
i18n.js
locales/en/common.json
locales/eo/common.json
locales/fr/common.json
locales/ja/common.json
i18n.js
module.exports = {
locales: ['en','fr','ja','eo'], // Array with the languages that you want to use
defaultLocale: 'en', // Default language of your website
pages: {
'*': ['common'], // Namespaces that you want to import per page (we stick to one namespace for all the application in this tutorial)
},
};
locales/en/common.json
{
"metaTitle": "Next.js Localization with Next-Translate",
"title": "Welcome to my i18n NextJS application!",
"description": "I'm using the Next-Translate library to translate this page."
}
locales/eo/common.json
{
"metaTitle": "Next.js Lokigo kun Next-Translate",
"title": "Bonvenon al mia aplikaĵo i18n NextJS!",
"description": "Mi uzas la bibliotekon Next-Translate por traduki ĉi tiun paĝon."
}
locales/fr/common.json
{
"metaTitle": "Localisation de Next.js avec Next-Translate",
"title": "Bienvenue dans mon application NextJS i18n !",
"description": "J'utilise la bibliothèque Next-Translate pour traduire cette page."
}
locales/ja/common.json
{
"metaTitle": "Next-Translate を使用した Next.js ローカリゼーション",
"title": "私の i18n NextJS アプリケーションへようこそ!",
"description": "Next-Translate ライブラリを使用してこのページを翻訳しています。"
}