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": "お問い合わせ"
  }
}

次に、それを <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} 構文を使って、dictionary のエントリに変数を追加します。

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

プレフィックスの使用

prefix を使って、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: 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...>"
  }
}

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

  • 開発: 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>
  );
}

次のステップ

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

Dictionaries