Config

loadTranslations

loadTranslations() 函数的 API 参考

概述

使用 loadTranslations 来指定翻译的加载行为。 在生产环境中,应用默认会从 GT 的 CDN(内容分发网络)加载翻译。 你可以提供一个 loadTranslations 函数,从其他来源加载翻译,例如:

  • 来自应用的打包产物(最常见)
  • 来自数据库
  • 来自 API
  • 来自不同的 CDN(内容分发网络)

我们已内置支持从应用打包产物中的本地文件加载翻译。 请按照本指南在你的 Next.js 应用中设置本地翻译(local translations)。

如果你希望手动定义自己的翻译,请查看自定义翻译指南 以及 loadDictionary 函数。

参考资料

参数

Prop

Type

描述

类型描述
locale需要加载其翻译内容的 locale。

返回值

一个 Promise<any>,其解析结果为一个字典,将各个 id 映射到指定 locale 的对应翻译。


设置

loadTranslations 定义为文件 loadTranslations.jsloadTranslations.ts 的默认导出,文件可放在 src/ 目录或项目根目录。 请确保该函数返回一个 Promise,解析为一个对象,其中包含指定 locale 的翻译。

src/loadTranslations.js
export default async function loadTranslations(locale) {
  const translations = await import(`../public/locales/${locale}.json`);
  return translations.default;
};

如果需要使用不同的名称或路径,请在 withGTConfig 中通过 loadTranslationsPath 参数传入相对路径。


示例

从包中读取翻译

src/loadTranslations.js
export default async function loadTranslations(locale) {
  const translations = await import(`../public/locales/${locale}.json`);
  return translations.default;
};

当配置为使用本地翻译时,gtx-cli translate 命令会将翻译保存到项目的文件树中。

npx gtx-cli translate

从内容分发网络(CDN)加载翻译内容

loadTranslations.js
export default async function loadTranslations(locale) {
  try {
    const translations = await fetch(`https://your-cdn.com/translations/${locale}.json`);
    const data = await translations.json();
    return data;
  } catch (e) {
    console.error(e);
    return {};
  }
};

从您自己的数据库加载翻译

loadTranslations.js
export default async function loadTranslations(locale) {
  try {
    const translations = await prisma.translation.findUnique({
      where: {
        locale: locale,
      },
    });
    return translations;
  } catch (e) {
    console.error(e);
    return {};
  }
};

问题: loadTranslationsloadDictionary 有何区别?

  • loadTranslations 用于为你的应用定义获取翻译的自定义加载逻辑。 这可以是从 CDN(内容分发网络)、数据库,或应用的打包产物中获取翻译。 这些翻译通常由机器生成,由 CLI(命令行界面)工具管理,不太适合由用户直接编辑。
  • loadDictionary 适用于将 gt-next 作为独立库使用的场景。 用户自带翻译内容,不依赖任何翻译基础设施。

注意事项

  • loadTranslations 允许你在生产环境中自定义应用的翻译加载方式。
  • 最常见的用法是添加本地翻译

后续步骤

本指南如何?