# gt: General Translation CLI tool: 使用自动 JSX 注入 URL: https://generaltranslation.com/zh/docs/cli/guides/using-auto-jsx.mdx --- title: 使用自动 JSX 注入 description: 如何在构建时通过自动 JSX 注入,将可翻译的 JSX 文本包装在 General Translation 组件中。 related: links: - /docs/cli/guides/using-autoderive - /docs/cli/guides/generating-translations - /docs/cli/guides/configuring - /docs/cli/guides/managing-translations --- 自动 JSX 注入会让编译器在构建时,自动将可翻译的 JSX 文本包装到 [``](/docs/react/reference/components/t) 组件中,这样你就不必手动添加了。 默认情况下,自动 JSX 注入是禁用的。它适用于 React 单页应用 (SPA) 和 Next.js 的 webpack 构建。 ## 启用自动 JSX 注入 [#enable] 安装编译器: ```bash npm install @generaltranslation/compiler ``` ```bash yarn add @generaltranslation/compiler ``` ```bash bun add @generaltranslation/compiler ``` ```bash pnpm add @generaltranslation/compiler ``` 在 `gt.config.json` 的 `files.gt.parsingFlags` 中设置 `enableAutoJsxInjection`。这样可使 CLI 提取与编译器转换保持同步。 ```json title="gt.config.json" { "files": { "gt": { "parsingFlags": { "enableAutoJsxInjection": true } } } } ``` ## 配置构建 [#configure-build] `gt.config.json` 标志会在 General Translation 编译器运行时生效。 ### React SPA 将 `@generaltranslation/compiler` 添加到你的 Vite、webpack、Rollup、Rspack 或 esbuild 配置中。有关适配器示例,请参阅 [使用 SPA 翻译进行开发](/docs/react/guides/developing-spa-translations#setup)。 ### Next.js 将 `gt-next` 配置为使用基于 Babel 的 webpack 编译器: ```ts title="next.config.ts" import { withGTConfig } from 'gt-next/config'; const nextConfig = {}; export default withGTConfig(nextConfig, { experimentalCompilerOptions: { type: 'babel', enableAutoJsxInjection: true, }, }); ``` 使用 webpack 运行开发服务器并进行生产构建: ```json title="package.json" { "scripts": { "dev": "next dev --webpack", "build": "next build --webpack" } } ``` Next.js 16 默认使用 Turbopack。Turbopack 会禁用 Babel 编译器,提示将跳过自动注入,并且不会包装 JSX。请参阅 [Next.js 编译器选项](/docs/react/nextjs/config#compiler-options)。 ## 工作方式 [#how] 如果不使用注入,则需要你自己包装可翻译的文本。 ```jsx import { T } from 'gt-react'; function Welcome() { return (

Welcome to our app

); } ``` Next.js 项目则从 [``](/docs/react/reference/components/t) 导入 `gt-next`。 启用注入后,编译器会检测可翻译的文本,并在构建时自动将其包裹起来。 ```jsx function Welcome() { return

Welcome to our app

; } ``` 你已经用 [``](/docs/react/reference/components/t) 包裹的文本,以及其他 General Translation 组件 (如 [``](/docs/react/reference/components/var)、[``](/docs/react/reference/components/branch)、[``](/docs/react/reference/components/plural) 和 [``](/docs/react/reference/components/derive)) 都将保持不变。 ## Next steps - /docs/cli/guides/using-autoderive - /docs/cli/guides/generating-translations - /docs/cli/guides/configuring - /docs/cli/guides/managing-translations