Next.js Internationalization (i18n) with next-i18next and Intlayer

    Both next-i18next and Intlayer are open-source internationalization (i18n) frameworks designed for Next.js applications. They are widely used for managing translations, localization, and language switching in software projects.

    Both solutions include three principal notions:

    1. コンテンツ宣言: アプリケーションの翻訳可能なコンテンツを定義するための方法。

      • i18nextの場合はresourceとして名付けられ、コンテンツ宣言は、1つまたは複数の言語の翻訳のためのキー-バリューのペアを含む構造化されたJSONオブジェクトです。詳細については、i18nextのドキュメントを参照してください。
      • Intlayerの場合はcontent declaration fileとして名付けられ、コンテンツ宣言は構造化データをエクスポートするJSON、JS、またはTSファイルになることができます。詳細については、Intlayerのドキュメントを参照してください。
    2. ユーティリティ: アプリケーション内でコンテンツ宣言を構築および解釈するためのツールであり、getI18n()useCurrentLocale()、またはuseChangeLocale()はnext-i18next用で、useIntlayer()またはuseLocale()はIntlayer用です。

    3. プラグインおよびミドルウェア: URLリダイレクション、バンドルの最適化などを管理するための機能であり、next-i18next/middlewareはnext-i18next用、intlayerMiddlewareはIntlayer用です。

    Intlayer vs. i18next: 主な違い

    i18nextとIntlayerの違いを探るには、私たちの次-i18next vs. next-intl vs. Intlayerブログ投稿をチェックしてください。

    Intlayerでnext-i18next辞書を生成する方法

    next-i18nextを使用する理由は?

    Intlayerのコンテンツ宣言ファイルは、通常、より良い開発者体験を提供します。これらは、2つの主な利点により、より柔軟でメンテナブルです。

    1. 柔軟な配置: Intlayerのコンテンツ宣言ファイルは、アプリケーションのファイルツリー内のどこにでも配置でき、未使用のコンテンツ宣言を残すことなく、コピーされたり削除されたりしたコンポーネントの管理を簡素化します。

      例ファイル構造:

      bash
      .└── src    └── components        └── MyComponent            ├── index.content.ts # コンテンツ宣言ファイル            └── index.tsx
    2. 中央集中的な翻訳: Intlayerは、すべての翻訳を単一のファイルに保存し、翻訳が欠けることがないようにします。TypeScriptを使用する場合は、欠けている翻訳が自動的に検出され、エラーとして報告されます。

    インストール

    bash
    npm install intlayer i18next next-i18next i18next-resources-to-backend

    Intlayerを構成してi18next辞書をエクスポートする

    i18nextリソースのエクスポートは、他のフレームワークとの1:1の互換性を保証するものではありません。問題を最小限に抑えるために、Intlayerベースの構成を維持することをお勧めします。

    i18nextリソースをエクスポートするには、intlayer.config.tsファイルでIntlayerを構成します。例の構成:

    intlayer.config.ts
    import { Locales, type IntlayerConfig } from "intlayer";const config: IntlayerConfig = {  internationalization: {    locales: [Locales.ENGLISH, Locales.FRENCH, Locales.SPANISH],    defaultLocale: Locales.ENGLISH,  },  content: {    dictionaryOutput: ["i18next"],    i18nextResourcesDir: "./i18next/resources",  },};export default config;

    i18next構成への辞書のインポート

    生成されたリソースをi18next構成にインポートするには、i18next-resources-to-backendを使用します。以下は例です:

    i18n/client.ts
    import i18next from "i18next";import resourcesToBackend from "i18next-resources-to-backend";i18next.use(  resourcesToBackend(    (language: string, namespace: string) =>      import(`../i18next/resources/${language}/${namespace}.json`)  ));

    コンテンツ宣言

    さまざまな形式のコンテンツ宣言ファイルの例:

    **/*.content.ts
    import { t, type Dictionary } from "intlayer";const content = {  key: "my-content",  content: {    myTranslatedContent: t({      en: "Hello World",      fr: "Bonjour le monde",      es: "Hola Mundo",    }),  },} satisfies Dictionary;export default content;

    next-i18nextリソースをビルドする

    next-i18nextリソースをビルドするには、以下のコマンドを実行します:

    bash
    npx run intlayer build

    これにより、./i18next/resourcesディレクトリにリソースが生成されます。期待される出力:

    bash
    .└── i18next    └── resources       └── ja           └── my-content.json       └── fr           └── my-content.json       └── es           └── my-content.json

    注意: i18nextの名前空間はIntlayerの宣言キーに対応します。

    Next.jsプラグインの実装

    構成が完了したら、次にIntlayerのコンテンツ宣言ファイルが更新されるたびにi18nextリソースを再ビルドするようにNext.jsプラグインを実装します。

    next.config.mjs
    import { withIntlayer } from "next-intlayer/server";/** @type {import('next').NextConfig} */const nextConfig = {};export default withIntlayer(nextConfig);

    Next.jsコンポーネントでコンテンツを使用する

    Next.jsプラグインを実装した後、そのコンテンツをコンポーネント内で使用できます:

    src/components/myComponent/index.tsx
    import type { FC } from "react";import { useTranslation } from "react-i18next";const IndexPage: FC = () => {  const { t } = useTranslation();  return (    <div>      <h1>{t("my-content.title")}</h1>      <p>{t("my-content.description")}</p>    </div>  );};export default IndexPage;

    このドキュメントを改善するアイデアがある場合は、GitHubでプルリクエストを送信することで自由に貢献してください。

    ブログへのGitHubリンク