Dictionaries

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

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

推奨: 新規プロジェクトでは<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 の利点

  • 一元管理 - すべての翻訳を1か所で管理
  • 業界標準 - 他の 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": "お問い合わせ"
  }
}

次に、それを<GTProvider> コンポーネントに渡します。

index.js
import dictionary from "./dictionary.js";
import config from "./gt.config.json";

createRoot(document.getElementById("root")!).render(
  <StrictMode>
    <GTProvider {...config} dictionary={dictionary}>
      <App />
    </GTProvider>
  </StrictMode>
);

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

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

import { useTranslations } from 'gt-react';

function MyComponent() {
  const d = useTranslations();
  
  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: '今日' })}</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: string) {
  const translations = await import(`./_gt/${locale}.json`);
  return translations.default;
}

それを <GTProvider> に渡します:

src/index.tsx
import loadTranslations from './loadTranslations';
import dictionary from './dictionary';

createRoot(document.getElementById("root")!).render(
  <StrictMode>
    <GTProvider 
      {...config} 
      dictionary={dictionary}
      loadTranslations={loadTranslations}
    >
      <App />
    </GTProvider>
  </StrictMode>
);

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 key を用いて、dictionary のエントリをオンデマンドで翻訳
  • 本番: すべての 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>
  );
}

次のステップ

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