# General Translation React SDKs (gt-react, gt-next, gt-react-native): 使用 SPA 翻译进行开发
URL: https://generaltranslation.com/zh/docs/react/guides/developing-spa-translations.mdx
---
title: 使用 SPA 翻译进行开发
description: 介绍如何在开发单页 React 应用时预览 General Translation 的翻译。
related:
links:
- /docs/react/guides/storing-translations
- /docs/react/guides/configuring
- /docs/react/guides/translating-jsx
- /docs/react/guides/managing-locales
---
开发翻译让你可以在编辑 SPA 时预览已翻译内容。它需要 GT 编译器 和开发 API 密钥。
**前提条件:**
* 一个已按 [SPA Quickstart](/docs/react/react-spa-quickstart) 配置好的单页 React 应用
* 一个以 `gtx-dev-` 开头的开发 API 密钥
**CommonJS 限制:** 开发时的热重载需要 ESM,因为 编译器 会注入顶层 `await`。它不适用于编译为 CommonJS 的应用。生产翻译仍可配合 [SPA Quickstart](/docs/react/react-spa-quickstart) 中的 CommonJS 启动模式使用。
## 设置 [#setup]
### 1. 安装编译器
将 `@generaltranslation/compiler` 作为开发依赖安装:
```bash
npm i -D @generaltranslation/compiler
```
```bash
yarn add --dev @generaltranslation/compiler
```
```bash
bun add --dev @generaltranslation/compiler
```
```bash
pnpm add --save-dev @generaltranslation/compiler
```
### 2. 添加编译器插件
在 CLI 和编译器共用的配置中启用开发时的热重载:
```json title="gt.config.json"
{
"files": {
"gt": {
"output": "src/_gt/[locale].json",
"parsingFlags": {
"devHotReload": true
}
}
}
}
```
然后为你的打包工具添加相应的插件。
```ts title="vite.config.ts"
import react from '@vitejs/plugin-react';
import { vite as gtCompiler } from '@generaltranslation/compiler'; // [!code highlight]
import { defineConfig } from 'vite';
import gtConfig from './gt.config.json'; // [!code highlight]
export default defineConfig({
plugins: [react(), gtCompiler({ ...gtConfig })], // [!code highlight]
});
```
将 `dotenv` 安装为开发依赖,以便 webpack 能够读取 `.env` 和 `.env.local`,然后在其余插件之前添加编译器。使用 `DefinePlugin`,仅向浏览器代码暴露开发凭据:
```js title="webpack.config.mjs"
import { webpack as gtCompiler } from '@generaltranslation/compiler';
import dotenv from 'dotenv';
import webpack from 'webpack';
import gtConfig from './gt.config.json' with { type: 'json' };
dotenv.config({ path: '.env' });
dotenv.config({ path: '.env.local', override: true });
export default (_env, argv) => {
const isProduction = (argv.mode ?? 'production') === 'production';
return {
// 保留你现有的 webpack 设置。
plugins: [
gtCompiler({ ...gtConfig }),
new webpack.DefinePlugin({
'process.env.GT_PROJECT_ID': JSON.stringify(
isProduction ? '' : (process.env.GT_PROJECT_ID ?? '')
),
'process.env.GT_DEV_API_KEY': JSON.stringify(
isProduction ? '' : (process.env.GT_DEV_API_KEY ?? '')
),
}),
],
};
};
```
有关加载器、本地翻译文件和开发服务器设置,请参阅完整的 [`gt-react` webpack 示例](https://github.com/generaltranslation/gt/tree/main/examples/webpack-spa)。
请在其他 Rollup 插件之前注册编译器:
```js title="rollup.config.mjs"
import { rollup as gtCompiler } from '@generaltranslation/compiler';
export default {
input: 'src/index.ts',
plugins: [
gtCompiler(),
// 你的其他 Rollup 插件
],
};
```
Rollup 无法分析完全动态的翻译导入。请使用静态导入说明符列出每个区域设置:
```ts title="src/loadTranslations.ts"
const translationLoaders = {
es: () => import('./_gt/es.json'),
fr: () => import('./_gt/fr.json'),
};
export default async function loadTranslations(locale: string) {
const loader =
translationLoaders[locale as keyof typeof translationLoaders];
return loader ? (await loader()).default : {};
}
```
原生 Rollup 不提供 Vite 和 webpack 所示的开发凭据集成。源内容变更时,请重新生成本地翻译文件。请参阅完整的 [`gt-react` Rollup 示例](https://github.com/generaltranslation/gt/tree/main/examples/rollup-spa)。
将 Rspack 适配器添加到你的插件中:
```js title="rspack.config.mjs"
import { rspack as gtCompiler } from '@generaltranslation/compiler';
export default {
plugins: [gtCompiler()],
};
```
开发翻译还需要向浏览器代码暴露 `GT_PROJECT_ID` 和 `GT_DEV_API_KEY`,且不得在生产 bundle 中包含这两个值。
将 esbuild 适配器添加到 `plugins` 数组:
```js title="build.mjs"
import { build } from 'esbuild';
import { esbuild as gtCompiler } from '@generaltranslation/compiler';
await build({
entryPoints: ['src/index.tsx'],
bundle: true,
outdir: 'dist',
plugins: [gtCompiler()],
});
```
*注:esbuild 适配器不支持自动 JSX 注入。请显式包裹可翻译的 JSX,或在需要 `enableAutoJsxInjection` 时使用其他适配器。*
如需完整的 Vite 设置,请参阅完整的 [`gt-react` Vite 示例](https://github.com/generaltranslation/gt/tree/main/examples/vite-spa)。
### 3. 添加开发凭据
前往 [dash.generaltranslation.com](https://dash.generaltranslation.com/en-US/signin) 获取开发 API 密钥,或运行:
```bash
npx gt auth
```
然后将你的项目 ID 和开发 API 密钥添加到 `.env.local`,并将它们传入初始化函数:
```bash title=".env.local"
VITE_GT_PROJECT_ID="your-project-id"
VITE_GT_DEV_API_KEY="your-dev-api-key"
```
```ts
await initializeGTSPA({
...gtConfig,
projectId: import.meta.env.VITE_GT_PROJECT_ID,
devApiKey: import.meta.env.VITE_GT_DEV_API_KEY,
loadTranslations,
});
```
```bash title=".env.local"
GT_PROJECT_ID="your-project-id"
GT_DEV_API_KEY="your-dev-api-key"
```
```ts
await initializeGTSPA({
...gtConfig,
projectId: process.env.GT_PROJECT_ID,
devApiKey: process.env.GT_DEV_API_KEY,
loadTranslations,
});
```
上面的 webpack 配置会在生产构建中将这两个值都替换为空字符串,因此开发凭据不会被包含在生产 bundle 中。
**仅限开发环境:** 请使用以 `gtx-dev-` 开头的密钥。切勿在浏览器代码中暴露以 `gtx-api-` 开头的生产密钥。
### 4. 开始开发
启动开发服务器,并切换到非默认区域设置。编辑可翻译内容时,编译器会记录这些更改,`gt-react` 会请求更新后的开发翻译。
## Next steps
- /docs/react/guides/storing-translations
- /docs/react/guides/configuring
- /docs/react/guides/translating-jsx
- /docs/react/guides/managing-locales