# General Translation React SDKs (gt-react, gt-next): 在本地存储翻译 URL: https://generaltranslation.com/zh/docs/react/guides/storing-translations.mdx --- title: 在本地存储翻译 description: 介绍如何在 React、Next.js、TanStack Start 和 React Native 中,将 General Translation 的翻译打包到应用内,而不是从 CDN 加载。 related: links: - /docs/react/guides/configuring - /docs/react/guides/developing-spa-translations - /docs/react/guides/managing-locales - /docs/react/guides/translating-jsx --- 默认情况下,General Translation 会在运行时从其 CDN 加载翻译。或者,你也可以生成翻译文件,将它们打包到应用中,并自行加载。这样可以去除对运行时 CDN 的依赖,但代价是更新翻译时需要重新部署。 ## 配置本地输出路径 [#configure] 在 `gt.config.json` 中,使用 `[locale]` 占位符将 `gt` 文件的输出路径设置到源代码中的某个位置。所有框架的配置方式都相同。 ```json title="gt.config.json" { "defaultLocale": "en", "locales": ["es", "fr"], "files": { "gt": { "output": "src/_gt/[locale].json" } } } ``` ## 生成文件 [#generate] 运行 CLI 来翻译内容,并在该路径下为每个区域设置生成一个文件。 ```bash npx gt translate ``` 把它添加到构建流程中,这样这些文件就能保持最新状态——例如,`"build": "npx gt translate && vite build"` (或 `next build`、`expo export` 等) 。 ## 将它们加载到应用中 [#load] 提供一个用于导入某个区域设置文件的 [`loadTranslations`](/docs/react/reference/functions/load-translations) 回调。具体如何注册取决于你使用的框架。 将 `loadTranslations` 传给初始化调用。 ```tsx title="src/routes/root.tsx" import { initializeGT } from 'gt-react'; import gtConfig from '../../gt.config.json'; const loadTranslations = (locale: string) => import(`../_gt/${locale}.json`).then((m) => m.default); initializeGT({ ...gtConfig, loadTranslations }); ``` 在项目根目录创建一个 `loadTranslations.ts` 文件。`withGTConfig` 插件会自动检测它 (或者显式设置 `loadTranslationsPath`) 。 ```ts title="loadTranslations.ts" export default async function loadTranslations(locale: string) { const t = await import(`./_gt/${locale}.json`); return t.default; } ``` ```ts title="next.config.ts" import { withGTConfig } from 'gt-next/config'; export default withGTConfig(nextConfig, { loadTranslationsPath: './loadTranslations.ts' }); ``` 将 `loadTranslations` 传给初始化调用。 ```tsx import { initializeGT } from 'gt-tanstack-start'; import gtConfig from '../gt.config.json'; const loadTranslations = (locale: string) => import(`./_gt/${locale}.json`).then((m) => m.default); initializeGT({ ...gtConfig, loadTranslations }); ``` 将 `loadTranslations` 传给初始化调用。 ```tsx import { initializeGT } from 'gt-react-native'; import gtConfig from '../gt.config.json'; const loadTranslations = (locale: string) => import(`./_gt/${locale}.json`).then((m) => m.default); initializeGT({ ...gtConfig, loadTranslations }); ``` 配置本地加载器后,翻译内容会从你的 bundle 中读取,不会发起 CDN 请求。若要切换回 CDN 交付,请移除该加载器,改为提供 `projectId` (参见[配置 General Translation](/docs/react/guides/configuring#delivery)) 。 ## Next steps - /docs/react/guides/configuring - /docs/react/guides/developing-spa-translations - /docs/react/guides/managing-locales - /docs/react/guides/translating-jsx