# General Translation React SDKs (gt-react, gt-next): 配置 URL: https://generaltranslation.com/zh/docs/react/nextjs/config.mdx --- title: 配置 description: 使用 gt-next/config 中的 withGTConfig 插件在 Next.js 应用中配置 General Translation,包括其选项,以及使用本地翻译还是 CDN 翻译。withGTConfig 的 API 参考。 --- `withGTConfig` 是 `gt-next` 的配置插件。在 `next.config` 中用它包装你的 Next.js 配置,即可在构建时启用国际化。它会读取你的 `gt.config.json` 文件,将其与你传入的选项和环境变量合并,并设置编译器、翻译加载和请求处理。 本页介绍该插件及其选项。有关共享的 `gt.config.json` 区域设置和文件配置,请参阅 [`gt-react` 配置参考](/docs/react/reference/config);有关 CLI 端的 `files` schema,请参阅 [CLI 配置参考](/docs/cli/reference/config)。 ## 概览 [#overview] 从 `gt-next/config` 导入 `withGTConfig``,并用它包装你的 Next.js 配置。也可以将选项作为第二个参数传入,但大多数项目会把区域设置放在 `gt.config.json` 中。 ```ts title="next.config.ts" import { withGTConfig } from 'gt-next/config'; import type { NextConfig } from 'next'; const nextConfig: NextConfig = { // 你现有的 Next.js 配置 }; export default withGTConfig(nextConfig, { defaultLocale: 'en', locales: ['es', 'fr', 'ja'], }); ``` `withGTConfig` 必须在 `next.config` 中使用——这是将国际化接入构建流程的唯一地方。 ## 工作原理 [#how-it-works] * **配置解析。** 默认情况下,插件会加载 `./gt.config.json` (也会检查 `./.gt/gt.config.json` 和 `./.locadex/gt.config.json`) 。各项值会按以下优先级合并:**你传入的选项 > 环境变量 > `gt.config.json` > 默认值。** 如果 `gt.config.json` 和选项中对同一个键设置了不同的值,构建时会抛出冲突错误,因此请将每个值只放在一个地方。 * **凭据来自环境变量。** 你不能将 `projectId`、`apiKey` 或 `devApiKey` 作为选项传入——请将它们设置为环境变量 (参见 [Credentials](#credentials)) 。 * **区域设置标准化。** 启用 General Translation 服务后,区域设置代码会被标准化为规范的 BCP 47 格式;无效的区域设置会在构建时抛出错误。 * **翻译交付。** 如果解析到了 [`loadTranslations`](/docs/react/reference/functions/load-translations) 文件,就会从你的 bundle 中加载翻译;否则会从 General Translation CDN 拉取。参见 [本地翻译与 CDN 翻译](#translations)。 ## 凭据 [#credentials] 将你的项目 ID 和 API 密钥设置为环境变量,切勿将其配置为插件选项: | 变量 | 说明 | | -------------------------------------------------- | -------------------------------------------- | | `GT_PROJECT_ID` (or `NEXT_PUBLIC_GT_PROJECT_ID`) | 你的 General Translation 项目 ID。 | | `GT_API_KEY` | 生产环境 API 密钥 (前缀为 `gtx-api-`) ,供 CLI 和生产构建使用。 | | `GT_DEV_API_KEY` (or `NEXT_PUBLIC_GT_DEV_API_KEY`) | 开发 API 密钥 (前缀为 `gtx-dev-`) ,用于开发环境中的按需翻译。 | *警告:绝不要为生产环境 API 密钥添加 `NEXT_PUBLIC_` 前缀,也不要在生产环境中包含开发密钥——如果在 `NODE_ENV=production` 时存在 `GT_DEV_API_KEY`,构建会直接报错。* ## 选项 [#options] 所有选项均为可选项。区域设置选项通常是在 `gt.config.json` 中设置,而不是在这里。 ### 区域设置选项 [#locale-options] | 选项 | 描述 | 类型 | 可选 | 默认 | | ---------------------------------------------------------------- | ----------------- | ---------- | -- | ------- | | [`defaultLocale`](#default-locale) | 应用编写时使用的源区域设置。 | `string` | 是 | `en` | | [`locales`](#locales) | 要翻译到的目标区域设置。 | `string[]` | 是 | `[]` | | [`ignoreBrowserLocales`](#ignore-browser-locales) | 检测时忽略浏览器的首选区域设置。 | `boolean` | 是 | `false` | | [`disableInvalidLocaleWarning`](#disable-invalid-locale-warning) | 不显示有关无效请求区域设置的警告。 | `boolean` | 是 | `false` | | [`description`](#description) | 应用的自然语言描述,用于辅助翻译。 | `string` | 是 | — | ### 翻译交付 [#delivery-options] | 选项 | 描述 | 类型 | 可选 | 默认值 | | ------------------------------------------------- | ------------------------------------------------------------------------------ | ---------------- | -- | ------------------ | | [`runtimeUrl`](#runtime-url) | General Translation API 的基础 URL。空字符串会禁用运行时翻译。 | `string \| null` | 是 | GT 运行时 | | [`cacheUrl`](#cache-url) | 缓存翻译的 URL。 | `string \| null` | 是 | GT CDN | | [`cacheExpiryTime`](#cache-expiry-time) | 本地缓存翻译失效前的毫秒数。 | `number` | 是 | `60000` | | [`loadTranslationsPath`](#load-translations-path) | 自定义 `loadTranslations` 文件的路径。 | `string` | 是 | 自动解析 | | [`loadDictionaryPath`](#load-dictionary-path) | 自定义 [`loadDictionary`](/docs/react/reference/functions/load-dictionary) 文件的路径。 | `string` | 是 | 自动解析 | | [`dictionary`](#dictionary) | 你的字典文件路径。 | `string` | 是 | 自动解析 | | [`config`](#config-path) | `gt.config.json` 文件的路径。 | `string` | 是 | `./gt.config.json` | ### 渲染 [#rendering-options] | 选项 | 描述 | 类型 | 可选 | 默认值 | | ------------------------------------ | --------------- | -------- | -- | --- | | [`renderSettings`](#render-settings) | 运行时翻译在加载时的渲染方式。 | `object` | 是 | 见下文 | ### 性能 [#performance-options] | 选项 | 描述 | 类型 | 可选 | 默认值 | | --------------------------------------------------- | ---------------- | -------- | -- | ----- | | [`maxConcurrentRequests`](#max-concurrent-requests) | 最大并发翻译请求数。 | `number` | 是 | `100` | | [`maxBatchSize`](#max-batch-size) | 每批的最大翻译数量。 | `number` | 是 | `25` | | [`batchInterval`](#batch-interval) | 批量请求之间的间隔 (毫秒) 。 | `number` | 是 | `50` | ### 构建与集成 [#build-options] | 选项 | 描述 | 类型 | 可选 | 默认 | | -------------------------------------------------- | ------------------------------------------------------------------- | ------------------- | -- | -------- | | [`experimentalCompilerOptions`](#compiler-options) | 编译器插件设置。 | `object` | 是 | 见下文 | | [`headersAndCookies`](#headers-and-cookies) | 自定义区域设置请求头和 Cookie 名称。 | `object` | 是 | 见下文 | | [`getLocalePath`](#request-function-paths) | 自定义 [`getLocale`](/docs/node/reference/functions/get-locale) 函数的路径。 | `string` | 是 | — | | [`getRegionPath`](#request-function-paths) | 自定义 `getRegion` 函数的路径。 | `string` | 是 | — | | [`pathRegex`](#path-regex) | 将 i18n 中间件限制为仅作用于匹配的路径名。 | `string` | 是 | — | | [`eslint`](#eslint-options) | 生成 General Translation 的 ESLint 配置。 | `boolean` | 是 | `true` | | [`eslintSeverity`](#eslint-options) | 生成的 ESLint 规则的严重程度。 | `'error' \| 'warn'` | 是 | `'warn'` | | [`overwriteESLintConfig`](#eslint-options) | 覆盖现有的 `eslint.config.mjs`。 | `boolean` | 是 | `false` | ### `defaultLocale` [#default-locale] **类型** `string` · **可选** · **默认值** `en` 你的应用所使用的源区域设置。缺少翻译时,会使用该区域设置作为后备。 ### `locales` [#locales] **类型** `string[]` · **可选** · **默认值** `[]` 要翻译成的目标区域设置。若请求的区域设置不受支持,会先回退到最接近的匹配项,再回退到 `defaultLocale`。请从[支持的区域设置](/docs/platform/dashboard/reference/supported-locales)中选择。 ### `ignoreBrowserLocales` [#ignore-browser-locales] **类型** `boolean` · **可选** · **默认值** `false` 当设为 `true` 时,进行区域设置检测时会忽略浏览器的 `Accept-Language` 首选项。 ### `disableInvalidLocaleWarning` [#disable-invalid-locale-warning] **类型** `boolean` · **可选** · **默认值** `false` 当设为 `true` 时,将不再显示有关无效请求区域设置的警告。 ### `description` [#description] **Type** `string` · **可选** 应用的自然语言描述。它会作为上下文一并发送,以提升翻译质量。 ### `runtimeUrl` [#runtime-url] **类型** `string | null` · **可选** · **默认值** General Translation 运行时 General Translation API 的基础 URL,用于按需翻译。将其设为空字符串可完全禁用运行时翻译。 ### `cacheUrl` [#cache-url] **Type** `string | null` · **可选** · **默认值** General Translation CDN 缓存翻译内容的 URL 来源。可将其指向自定义缓存主机,或将其设为 `null` 以禁用远程加载。 ### `cacheExpiryTime` [#cache-expiry-time] **类型** `number` · **可选** · **默认值** `60000` 本地缓存的翻译在失效前可保留的毫秒数。此默认值适用于未使用开发密钥时,在生产环境中进行远程加载的情况。 ### `loadTranslationsPath` [#load-translations-path] **类型** `string` · **可选** 用于[本地翻译](#translations)的自定义 `loadTranslations` 文件路径。默认情况下,插件会在你的项目根目录或 `src/` 目录下自动查找 `loadTranslations.[js|ts]` 文件。 ### `loadDictionaryPath` [#load-dictionary-path] **类型** `string` · **可选** 自定义 `loadDictionary` 文件的路径。默认情况下,插件会自动在项目根目录或 `src/` 中查找 `loadDictionary.[js|ts]` 文件。 ### `dictionary` [#dictionary] **类型** `string` · **可选** 你的词典文件路径。位于项目根目录或 `src/` 中、名为 `dictionary.[js|ts|json]` 的文件会被自动识别。 ### `config` [#config-path] **类型** `string` · **可选** · **默认值** `./gt.config.json` 要加载的 `gt.config.json` 文件路径。 ### `renderSettings` [#render-settings] **类型** `{ method: 'skeleton' | 'replace' | 'default'; timeout?: number }` · **可选** 控制运行时翻译加载期间内容的渲染方式。仅适用于按需执行的翻译;已缓存的翻译会立即渲染。 * `method` — 以下之一: * `skeleton` — 等待期间不渲染任何内容 (即空片段) 。 * `replace` — 等待期间渲染默认语言的内容。 * `default` — 对相同语言的区域设置 (如 `en-US` 和 `en-GB`) ,其行为与 `replace` 相同;对不同语言,则与 `skeleton` 相同。 * `timeout` — 渲染方式超时后回退到原始内容前的毫秒数。开发环境默认为 `8000`,生产环境默认为 `12000`。 ```ts title="next.config.ts" export default withGTConfig(nextConfig, { renderSettings: { method: 'skeleton', timeout: 10000, }, }); ``` ### `maxConcurrentRequests` [#max-concurrent-requests] **类型** `number` · **可选** · **默认值** `100` 向 General Translation API 发起翻译请求时的最大并发数。 ### `maxBatchSize` [#max-batch-size] **Type** `number` · **可选** · **默认值** `25` 单次批量请求中可分组的最大翻译数量。 ### `batchInterval` [#batch-interval] **类型** `number` · **可选** · **默认值** `50` 两次批量翻译请求之间的等待毫秒数,用于控制请求速率。 ### `experimentalCompilerOptions` [#compiler-options] **类型** `object` · **可选** 编译器插件的配置,用于在构建时分析你的源代码。字段如下: | Field | Description | Type | Default | | -------------------- | -------------- | ---------------------------------------------------- | -------- | | `type` | 使用哪个编译器插件。 | `'babel' \| 'swc' \| 'none'` | `'none'` | | `logLevel` | 编译器的日志详细级别。 | `'silent' \| 'error' \| 'warn' \| 'info' \| 'debug'` | `'warn'` | | `compileTimeHash` | 在构建时预先计算翻译哈希值。 | `boolean` | `true` | | `disableBuildChecks` | 禁用构建时验证检查。 | `boolean` | `false` | ### `headersAndCookies` [#headers-and-cookies] **类型** `object` · **可选** 覆盖 `gt-next` 用于传递区域设置及相关请求状态的 请求头 和 cookie 名称。字段包括:`localeHeaderName`、`localeCookieName`、`enableI18nCookieName`、`referrerLocaleCookieName`、`localeRoutingEnabledCookieName` 和 `resetLocaleCookieName`。每个字段默认使用该库的标准名称。 ### 请求函数路径 [#request-function-paths] **类型** `string` · **可选** `getLocalePath` 和 `getRegionPath` 用于指向自定义的 `getLocale` 和 `getRegion` 实现,让你可以覆盖请求的区域设置和区域的解析方式。 ### `pathRegex` [#path-regex] **类型** `string` · **可选** 一个 JavaScript 正则表达式源字符串。设置后,i18n 中间件和客户端区域设置路由边界只会在与其匹配的路径名上运行——例如,`^/(?!uk(?:/|$)).*` 可用于跳过 `/uk` 下的所有内容。无效的表达式会在构建时报错。这个选项应在 `withGTConfig` 上设置,而不是在 [`createNextMiddleware`](/docs/react/nextjs/reference/functions/create-next-middleware) 上设置;插件 会在构建时将其传递给中间件。 **手动处理区域设置别名:** 被过滤的路径会绕过区域设置规范化。如果你配置的 locales 是 `en`、`en-GB` 和 `fr`,那么路径段 `uk` 不会被识别为 `en-GB`。自定义 `getLocale()` 函数必须为 `uk` 返回 `en-GB`: ```ts title="getLocale.ts" import { locale } from 'next/root-params'; export default async function getLocale() { const pathnameLocale = await locale(); if (pathnameLocale === 'uk') return 'en-GB'; return pathnameLocale; } ``` 调用 `registerLocale()` 前,也要应用同样的映射: ```ts registerLocale(locale === 'uk' ? 'en-GB' : locale); ``` 如果 `getLocale()` 或 `registerLocale()` 收到未知的区域设置,`gt-next` 会发出警告,并回退到 `defaultLocale`。 ### ESLint 选项 [#eslint-options] * `eslint` (`boolean`, 默认 `true`) — 在 setup 期间生成 General Translation 的 ESLint 配置。 * `eslintSeverity` (`'error' | 'warn'`, 默认 `'warn'`) — 生成的规则的严重程度级别。 * `overwriteESLintConfig` (`boolean`, 默认 `false`) — 允许覆盖现有的 `eslint.config.mjs`。 关于这些规则本身,请参阅 [Linting your code](/docs/react/guides/linting-your-code)。 ## 本地翻译与 CDN 翻译 [#translations] 默认情况下,`gt-next` 会在运行时从 General Translation CDN 拉取翻译;当你运行 `npx gt translate` 时,译文内容会自动上传到那里。或者,你也可以将翻译打包进应用,并在本地加载。 本地翻译加载更快,也支持离线使用,但代价是包体更大,而且每次内容变更都需要重新部署。要使用本地翻译,请添加一个 `loadTranslations` 文件,使其返回某个区域设置的翻译内容: ```ts title="src/loadTranslations.ts" export default async function loadTranslations(locale: string) { const translations = await import(`../public/_gt/${locale}.json`); return translations.default; } ``` `withGTConfig` 会自动在项目根目录或 `src/` 目录中查找 `loadTranslations.[js|ts]` 文件 (也可以显式设置 [`loadTranslationsPath`](#load-translations-path)) 。然后让 CLI 指向同一目录,这样 `npx gt translate` 就会把文件写入该目录。完整 workflow 请参阅[在本地存储翻译](/docs/react/guides/storing-translations)。 ## 返回 [#returns] `withGTConfig` 会返回一个经过 General Translation 设置增强的 `NextConfig` 对象。如果配置存在冲突、缺少必需的 API 密钥、在 General Translation 服务中使用了无效的区域设置,或在生产环境中存在开发密钥,它会在构建时报错。