Dictionaries

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

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

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

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

Dictionary パターン

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

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

コンポーネントパターン

// コンポーネントを直接使用(推奨)
function MyComponent() {
  return <T><div>こんにちは、世界!</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 のエントリにアクセスできます。

クライアントコンポーネント(Client Components)

import { useTranslations } from 'gt-next';

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

Server Components(サーバーコンポーネント)

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>
  );
}

Variables の使用

{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...>"
  }
}

開発環境と本番環境の挙動

  • 開発: dictionary のエントリは Dev API key を用いてオンデマンドで翻訳されます
  • 本番: すべての dictionary の翻訳はビルド時に事前生成されます

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

dictionaries と <T> コンポーネント は併用できます。

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>
  );
}

次のステップ

このガイドはいかがですか?