# General Translation React SDKs (gt-react, gt-next, gt-react-native): 配置 Rollup SPA
URL: https://generaltranslation.com/zh/docs/react/guides/spa/configuring-rollup-spa.mdx
Docs index: https://generaltranslation.com/llms.txt
Description: 如何在由 Rollup 驱动的单页 React 应用程序中配置 gt-react。

配置应用程序运行时，并可选择将生成的翻译目录与 Rollup 构建一起打包。

本指南用于准备应用程序运行时。请单独标记需要翻译的面向用户内容。

## React Rollup SPA 设置 [#setup]

在应用入口文件运行之前初始化 `gt-react`。

### 1. 安装 gt-react

请使用仓库首选的包管理器安装最新版本的 `gt-react`。若已安装，请跳过此步骤。

### 2. 在项目根目录添加 `gt.config.json` 文件

在项目根目录添加 `gt.config.json` 文件。该文件包含 `gt-react` package 的配置。

以项目中已有的区域设置或提供给 setup 任务的区域设置为准。保留现有的 `locales` 和 `defaultLocale` 值。以下值仅作示例。如果项目没有区域设置配置，请勿根据这些示例推断所需的区域设置。

```json title="gt.config.json"
{
  "defaultLocale": "en",
  "locales": ["fr", "de"]
}
```

可选的 [`src`](/docs/cli/reference/config#src) 字段用于指定 GT 扫描内联内容时所使用的源文件；省略时，默认使用 `src`、`app`、`pages` 和 `components` 目录下的以下 JavaScript 和 TypeScript glob 模式：

```json title="gt.config.json"
{
  "defaultLocale": "en",
  "locales": ["fr", "de"],
  "src": [
    "src/**/*.{js,jsx,ts,tsx}",
    "app/**/*.{js,jsx,ts,tsx}",
    "pages/**/*.{js,jsx,ts,tsx}",
    "components/**/*.{js,jsx,ts,tsx}"
  ]
}
```

### 3. 初始化库

在应用渲染或导入使用模块级翻译函数的模块之前，使用 [`initializeGTSPA`](/docs/react/reference/config#initialize-spa) 初始化库。

在应用现有入口文件旁新建一个引导文件。本示例中，原入口文件为 `src/main.tsx`，新建的引导文件为 `src/index.ts`。将 Rollup 现有的 `input` 配置改为指向该引导文件。保留所有其他构建设置。

引导文件和翻译加载器都会导入 JSON 文件。如果项目尚未配置对 JSON 模块的支持，请使用仓库首选的包管理器将 `@rollup/plugin-json` 安装为开发依赖，并将其添加到现有插件列表中。保留所有现有插件及其配置。

```js title="rollup.config.mjs"
import json from '@rollup/plugin-json';

export default {
  // ...项目现有的选项
  input: 'src/index.ts',
  plugins: [
    // ...项目现有的插件
    json(),
  ],
};
```

如果开发环境中的 HTML 直接引用了原始源条目，也请一并更新：

```html title="index.html"
<!-- <script type="module" src="/src/main.tsx"></script> -->
<script type="module" src="/src/index.ts"></script>
```

然后初始化 GT，并仅在初始化完成后动态导入原始入口文件。Rollup 参考应用会生成 ESM，并支持顶层 await：

```ts title="src/index.ts"
import { initializeGTSPA } from 'gt-react';
import gtConfig from '../gt.config.json';

await initializeGTSPA(gtConfig);

await import('./main'); // 仅在 GT 已就绪后再渲染应用
```

如果现有 Rollup 输出格式或目标不支持顶层 await，请勿仅为此配置而更改它。请改用异步引导函数：

```ts title="src/index.ts"
import { initializeGTSPA } from 'gt-react';
import gtConfig from '../gt.config.json';

async function bootstrap() {
  await initializeGTSPA(gtConfig);
  await import('./main');
}

void bootstrap();
```

## 加载翻译 [#translations]

调用 [`initializeGTSPA`](/docs/react/reference/config#initialize-spa) 时若未提供 [`loadTranslations`](/docs/react/reference/functions/load-translations) 函数，运行时仅在存在 [`projectId`](/docs/react/reference/config#project-id) 时才会从 General Translation CDN 加载翻译。若要将翻译目录打包到应用程序 bundle 中，请配置输出路径及相应的加载器。以下步骤使用 `src/_gt/[locale].json`。

### 1. 更新配置

将 `files.gt.output` 设置为 CLI 应写入生成的翻译文件的位置。

仅添加或合并 `files.gt.output` 设置。保留项目现有的 `locales` 和 `defaultLocale`；下方所示的值仅为示例，不能替换项目中已配置的区域设置。

在由 Rollup 驱动的应用中，通常会将翻译存储在 `src/_gt` 目录中。这样 Rollup 就能将翻译模块打包到应用 bundle 中。

```json title="gt.config.json"
{
  "locales": ["fr", "zh"],
  "defaultLocale": "en",
  "files": {
    "gt": {
      "output": "src/_gt/[locale].json"
    }
  }
}
```

### 2. 添加存根文件

请为 `gt.config.json` 中已配置的每个目标区域设置创建一个空的 JSON 文件，但默认区域设置除外。这些存根文件可让导入在翻译包尚不存在时完成解析。下面的 `fr` 和 `zh` 文件对应本指南中的示例配置；请改为根据项目实际配置的目标区域设置创建文件。如果尚未配置目标区域设置，请勿自行添加区域设置或创建占位符文件。

<Files>
  <Folder name="src">
    <Folder name="_gt">
      <File name="fr.json" />

      <File name="zh.json" />
    </Folder>
  </Folder>
</Files>

```json title="src/_gt/fr.json"
{}
```

```json title="src/_gt/zh.json"
{}
```

### 3. 添加加载器

创建 `src/loadTranslations.ts` 来加载翻译。它必须解析到与 `files.gt.output` 中配置相同的输出位置。

在 `translationLoaders` 中显式列出每个已配置的目标区域设置。每个加载器都必须使用字面量导入路径，以便 Rollup 能在构建时发现并输出每个翻译文件。下方的 `fr` 和 `zh` 条目与本指南的示例配置相对应；请改为使用项目中实际配置的目标区域设置。

```ts title="src/loadTranslations.ts"
const translationLoaders = {
  fr: () => import('./_gt/fr.json'),
  zh: () => import('./_gt/zh.json'),
};

export default async function loadTranslations(locale: string) {
  try {
    const loader =
      translationLoaders[locale as keyof typeof translationLoaders];
    if (!loader) {
      console.warn(`No translations found for locale "${locale}"`);
      return {};
    }
    const translations = await loader();
    return translations.default;
  } catch (error) {
    console.warn(`No translations found for locale "${locale}"`, error);
    return {};
  }
}
```

### 4. 更新初始化器

更新初始化器以使用新的加载器函数。保留应用当前使用的顶层 await 或异步引导函数形式。

```ts title="src/index.ts"
import { initializeGTSPA } from 'gt-react';
import gtConfig from '../gt.config.json';
import loadTranslations from './loadTranslations';

await initializeGTSPA({ ...gtConfig, loadTranslations });

await import('./main');
```

## Next steps

- /docs/react/guides/spa/internationalizing-react-spa
- /docs/react/guides/developing-spa-translations
- /docs/react/guides/storing-translations
- /docs/react/guides/managing-locales

## Sitemap

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