字典

如何使用传统的基于字典的翻译模式

字典是一种传统做法,将翻译以键值对的形式组织在嵌套对象中。虽然推荐使用 <T> components,但在从其他 i18n 库迁移,或当你更倾向于集中式管理翻译时,字典依然有用。

建议: 新项目请使用 <T> components。字典主要用于迁移场景以及与现有翻译流程的兼容。

字典与组件翻译对比

字典模式

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

权衡取舍

字典优势

  • 集中存储 - 所有翻译统一管理
  • 行业标准 - 延续其他 i18n 库的常见模式
  • 迁移友好 - 轻松迁移现有翻译

字典的劣势

  • 复杂性 - 需要更多设置与配置
  • 可维护性 - 内容与使用分离,更新更困难
  • 可调试性 - 更难将翻译追溯到组件
  • 可读性 - 键名无法体现实际内容

快速上手

步骤 1:创建字典

在项目根目录或 src 目录下创建一个字典文件:

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 目录中检测到字典文件。

步骤 2:在组件中使用

通过 useTranslations 钩子可以访问字典条目:

客户端组件

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} 语法将变量添加到字典项中:

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

多语种支持

自动翻译(推荐)

大多数用户应使用 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 会基于你的基础字典自动生成其他语言的翻译。运行 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 && <...你的构建命令...>"
  }
}

开发环境与生产环境的行为差异

  • 开发环境:使用 Dev API key 按需翻译字典条目
  • 生产环境:在构建阶段预先生成所有字典翻译

与组件配合使用

dictionaries 与 <T> 组件 可以配合工作:

function MixedApproach() {
  const d = useTranslations();
  
  return (
    <div>
      {/* 简单字符串的字典 */}
      <h1>{d('page.title')}</h1>
      
      {/* 处理复杂 JSX 的 T 组件 */}
      <T>
        <p>这是一条包含 <strong>复杂信息</strong> 和 <a href="/link">链接</a> 的内容。</p>
      </T>
      
      {/* 表单标签的字典 */}
      <label>{d('forms.email')}</label>
    </div>
  );
}

下一步

本指南如何?