Dictionaries

従来型のdictionaryベース翻訳パターンの使い方

dictionariesは、翻訳をキーと値のペアを持つ入れ子オブジェクトで整理する従来の手法を提供します。推奨は<T> componentsですが、他のi18nライブラリからの移行時や、翻訳を一元管理したい場合にdictionariesは有用です。

推奨: 新規プロジェクトでは<T> componentsを使用してください。dictionariesは主に既存の翻訳ワークフローとの移行や互換性のためにサポートされています。

dictionary とコンポーネントによる翻訳の比較

dictionary パターン

// dictionary.ts
export default {
  greetings: {
    hello: 'こんにちは、世界!',
    welcome: 'ようこそ、{name}さん!'
  }
};

// コンポーネントの使用例
function MyComponent() {
  const d = useTranslations();
  return <div>{d('greetings.hello')}</div>;
}

コンポーネント パターン

// 直接コンポーネント使用 - 推奨
function MyComponent() {
  return <T><div>Hello, world!</div></T>;
}

トレードオフ

dictionary の利点

  • 一元管理 - すべての翻訳を一か所に集約
  • 業界標準 - 他の i18n ライブラリでおなじみのパターン
  • 移行に優しい - 既存の翻訳を容易に移行可能

dictionary のデメリット

  • 複雑さ - 追加のセットアップや設定が必要になる
  • 保守性 - コンテンツが利用箇所と分離されるため、更新が難しくなる
  • デバッグ容易性 - 翻訳をコンポーネントまで遡って追跡しにくい
  • 可読性 - キーからは実際のコンテンツが分からない

クイックスタート

ステップ 1: dictionary を作成

プロジェクトのルートまたは src ディレクトリに dictionary ファイルを作成します。

dictionary.ts
const dictionary = {
  greetings: {
    hello: 'こんにちは、世界!',
    welcome: 'アプリへようこそ!'
  },
  navigation: {
    home: 'ホーム',
    about: 'アプリについて',
    contact: 'お問い合わせ'
  }
};

export default dictionary;

または JSON 形式を使用します:

dictionary.json
{
  "greetings": {
    "hello": "こんにちは、世界!",
    "welcome": "私たちのアプリへようこそ!"
  },
  "navigation": {
    "home": "ホーム", 
    "about": "概要",
    "contact": "お問い合わせ"
  }
}

withGTConfig 関数は、プロジェクトのルートまたは src ディレクトリにある dictionary ファイルを自動的に検出します。

ステップ 2: コンポーネントでの使用

useTranslations フックを使うと、dictionary のエントリにアクセスできます。

クライアントコンポーネント

import { useTranslations } from 'gt-next';

function MyComponent() {
  const d = useTranslations();
  
  return (
    <div>
      <h1>{d('greetings.hello')}</h1>
      <p>{d('greetings.welcome')}</p>
    </div>
  );
}

サーバーコンポーネント

import { getTranslations } from 'gt-next/server';

async function MyServerComponent() {
  const d = await getTranslations();
  
  return (
    <div>
      <h1>{d('greetings.hello')}</h1>
      <p>{d('greetings.welcome')}</p>
    </div>
  );
}

Variable の使用

{variable} 構文を使って dictionary のエントリに variables を追加します。

dictionary.ts
const dictionary = {
  user: {
    greeting: 'こんにちは、{name}さん!',
    itemCount: '{count}個のアイテムがあります',
    orderTotal: '合計: ${amount}'
  }
};
function UserDashboard() {
  const d = useTranslations();
  
  return (
    <div>
      <h1>{d('user.greeting', { name: 'Alice' })}</h1>
      <p>{d('user.itemCount', { count: 5 })}</p>
      <p>{d('user.orderTotal', { amount: 99.99 })}</p>
    </div>
  );
}

プレフィックスの使用

プレフィックスを使って、dictionary へのアクセス範囲を特定のセクションに限定します:

dictionary.ts
const dictionary = {
  dashboard: {
    header: {
      welcome: 'おかえりなさい!',
      lastLogin: '最終ログイン: {date}'
    },
    stats: {
      totalUsers: '総ユーザー数: {count}',
      activeUsers: 'アクティブユーザー数: {count}'
    }
  }
};
function DashboardHeader() {
  // プレフィックスにより 'dashboard.header' へのアクセスを制限
  const d = useTranslations('dashboard.header');
  
  return (
    <header>
      <h1>{d('welcome')}</h1> {/* -> dashboard.header.welcome */}
      <p>{d('lastLogin', { date: 'Today' })}</p> {/* -> dashboard.header.lastLogin */}
    </header>
  );
}

function DashboardStats() {
  // 統計セクション用の異なるプレフィックス
  const d = useTranslations('dashboard.stats');
  
  return (
    <div>
      <p>{d('totalUsers', { count: 1000 })}</p> {/* -> dashboard.stats.totalUsers */}
      <p>{d('activeUsers', { count: 150 })}</p> {/* -> dashboard.stats.activeUsers */}
    </div>
  );
}

多言語対応

自動翻訳(推奨)

ほとんどのユーザーは、ベースの dictionary から翻訳を自動生成するために loadTranslations を使用するのがよいでしょう。

dictionary.ts
const dictionary = {
  common: {
    save: '保存',
    cancel: 'キャンセル',
    delete: '削除'
  },
  forms: {
    required: 'この項目は必須です',
    email: '有効なメールアドレスを入力してください'
  }
};

export default dictionary;

生成済みの翻訳ファイルを読み込むための loadTranslations 関数を作成します。

src/loadTranslations.ts
export default async function loadTranslations(locale) {
  const translations = await import(`../public/locales/${locale}.json`);
  return translations.default;
}

withGTConfig は、src/ ディレクトリまたはプロジェクトのルートから loadTranslations.[js|ts] ファイルを自動的に検出します。

GT は、ベースの dictionary に基づいて他言語の翻訳を自動生成します。設定済みのすべての言語向けの翻訳を生成するには、npx gtx-cli translate を実行してください。

手動翻訳ファイル(移行)

他の i18n ライブラリから移行する場合や手動で翻訳を管理する場合は、loadDictionary を使用してください。

src/loadDictionary.ts
export default async function loadDictionary(locale: string) {
  const translations = await import(`../public/locales/${locale}.json`);
  return translations.default;
}

これは public/locales/ ディレクトリから JSON 形式の翻訳ファイルを読み込みます。

es.json
fr.json
de.json

最適な方法を選びましょう: 自動翻訳生成を利用する新規プロジェクトには loadTranslations を、既存の翻訳ファイルを移行する場合は loadDictionary を使用してください。

本番環境の設定

ビルドプロセス

ビルドパイプラインに翻訳を追加する:

package.json
{
  "scripts": {
    "build": "npx gtx-cli translate && <...YOUR_BUILD_COMMAND...>"
  }
}

開発環境と本番環境の動作の違い

  • 開発: Dev APIキーを使用し、dictionary のエントリをオンデマンドで翻訳
  • 本番: すべての dictionary の翻訳をビルド時に事前生成

コンポーネントとの組み合わせ

dictionaries と <T> components は併用できます。

function MixedApproach() {
  const d = useTranslations();
  
  return (
    <div>
      {/* シンプルな文字列用のdictionary */}
      <h1>{d('page.title')}</h1>
      
      {/* 複雑なJSX用の<T>コンポーネント */}
      <T>
        <p>これは<a href="/link">リンク</a>付きの<strong>複雑なメッセージ</strong>です。</p>
      </T>
      
      {/* フォームラベル用のdictionary */}
      <label>{d('forms.email')}</label>
    </div>
  );
}

次のステップ

このガイドはどうでしたか?

Dictionaries