# General Translation Changelog: gt-i18n 0.9.0: 基于词典的翻译
URL: https://generaltranslation.com/zh/blog/gt-i18n_v0_9_0.mdx
Docs index: https://generaltranslation.com/llms.txt
Description: 
Authors: Ernest McCarter
Published: 2026-05-07

## 概述

`gt-i18n` 现在为框架集成提供基于词典的翻译。在 Node.js 应用中，请使用 `gt-node` 导出的公开 [`getTranslations()`](/docs/node/reference/functions/get-translations)；`gt-i18n@0.9.0` 并未从其包根目录导出该函数。

| 软件包       | 版本      |
| --------- | ------- |
| `gt-i18n` | `0.9.0` |
| `gt-node` | `0.7.0` |

## 设置

在项目根目录创建一个 `dictionary.json` 文件，并填入源字符串 (英文) ：

```json title="dictionary.json"
{
  "greeting": {
    "hello": "Hello!"
  },
  "user": {
    "welcome": "Welcome, {name}!"
  },
  "errors": {
    "notFound": "Page not found",
    "unauthorized": "Access denied"
  }
}
```

当你运行 CLI ([`npx gt translate`](/docs/cli/reference/commands/translate)) 时，它会检测项目根目录中的 `dictionary.json`，并为你配置的各个区域设置生成翻译。

使用 [`initializeGT`](/docs/node/reference/functions/initialize-gt) 配置 Node.js 运行时：

```ts
import { initializeGT } from 'gt-node';
import dictionary from './dictionary.json';

initializeGT({
  defaultLocale: 'en',
  locales: ['en', 'es'],
  dictionary,
});
```

<Accordions>
  <Accordion title="使用你自己的词典">
    如果你想加载自己预先翻译好的词典，可以在初始化 `gt-node` 时传入一个异步的 [`loadDictionary`](/docs/node/reference/config#load-dictionary) 选项。你仍然需要显式提供默认词典——该加载器用于提供已翻译的区域设置：

    ```ts
    import { initializeGT } from 'gt-node';
    import dictionary from './dictionary.json';

    initializeGT({
      defaultLocale: 'en',
      locales: ['en', 'es'],
      dictionary,
      loadDictionary: async (locale) => {
        const dict = await import(`./locales/${locale}.json`);
        return dict.default;
      },
    });
    ```

    该加载器会提供你自己的翻译后的词典，而不是获取生成的词典。
  </Accordion>
</Accordions>

## 用法

基于上述源词典，调用 [`getTranslations()`](/docs/node/reference/functions/get-translations) 获取一个 `t` 函数，用于从你的词典中查找对应条目：

```ts
import { getTranslations, withGT } from 'gt-node';

await withGT('en', async () => {
  const t = await getTranslations();

  t('greeting.hello'); // "你好！"
  t('user.welcome', { name: 'Alice' }); // "欢迎，Alice！"
});
```

### 使用 `t.obj()` 获取子词典

`t()` 返回单个字符串。`t.obj()` 则会以对象形式返回词典中的整个子树：

```ts
// 在上面的 withGT callback 内部：
t('errors.notFound'); // "页面未找到"

const errors = t.obj('errors');
// { notFound: "页面未找到", unauthorized: "访问被拒绝" }
```

当翻译后的词典缺少某些键时，系统会从源词典中补上缺失的条目。这意味着部分翻译不会导致运行时错误——未翻译的键会回退到源文本。

## 查找行为

查找的解析由两条规则决定：

1. **缺少翻译 → 回退到默认区域设置。** 如果某个键存在于源词典中，但当前区域设置没有对应翻译，`t()` 会返回源文本。
2. **缺少源条目 → 报错。** 如果某个键根本不存在于源词典中，`t()` 就会抛出错误。这是有意为之——如果某个键没有在源词典中定义，那就是一个 bug，而不是缺少翻译。此行为将在即将进行的重构中应用到所有 GT 库。

第二条规则的前提是，翻译后的词典与源词典的结构保持一致，而这正是 GT 自动生成翻译的方式。

## 链接

* [PR #1359](https://github.com/generaltranslation/gt/pull/1359)
* [`getTranslations` API 参考文档](/docs/node/reference/functions/get-translations)
* [词典指南](/docs/react/guides/translating-with-dictionaries)

## Sitemap

See the full [sitemap](https://generaltranslation.com/sitemap.md) for all pages.
