0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Next.js: 簡単な多言語化

Last updated at Posted at 2022-05-17

簡単な多言語化の方法です。
次のようなページを作成します。

http://localhost:3000/
image.png

http://localhost:3000/en
image.png

プロジェクトの作成

npx create-next-app@latest proj01

サーバーの起動の確認

cd proj01
yarn dev

ページの改造

next.config.js
/** @type {import('next').NextConfig} */
const nextConfig = {
  reactStrictMode: true,
  i18n: {
	locales: ['en', 'ja'],
	defaultLocale: 'ja',
	},
}

module.exports = nextConfig
pages/index.js
import { useRouter } from "next/router";
import en from "../locales/en";
import ja from "../locales/ja";

export default function Home() {
   const { locale } = useRouter()

   const t = locale === "en" ? en : ja;

   return (
      <div>
         ...
         <p>{t.GREETING}</p>
         <h2>{t.SUBTITLE}</h2>
         <button>{t.TO_DASHBOARD}</button>
         <p>{t.DATE}</p>
      </div>
   )
}

ロケールの作成

locales/ja.js
export default {
  SUBTITLE: "「満足」を可視化しよう",
  TO_DASHBOARD: "ダッシュボードへ",
  DATE: "2022年5月17日 午後5時30分",
  GREETING: "下野市(しもつけし)は、栃木県南部に位置する人口約6万人の市。宇都宮市への通勤率は13.3%、小山市への通勤率は11.1%(いずれも平成22年国勢調査)。関東大都市圏に属する。",
  // ...
}
locales/en.js
// en.js
export default {
  SUBTITLE: "Visualize your customer happiness.",
  TO_DASHBOARD: "Go to dashboard",
  DATE: "May/17/2022 PM 17:30",
  GREETING: "Shimotsuke (下野市, Shimotsuke-shi) is a city located in Tochigi Prefecture, Japan. As of 1 August 2020, the city had an estimated population of 60,274 in 24,654 households, and a population density of 810 persons per km². The total area of the city is 74.59 square kilometres (28.80 sq mi).",
  // ...
}

サーバーの起動

yarn dev

日本語のページ
http://localhost:3000/

英語のページ
http://localhost:3000/en

vercel にデプロイ

GitLab 経由で、vercel にデプロイした様子です。
日本語のページ
image.png

英語のページ
image.png

0
0
0

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?