target 选项指定编译器应为哪个 React 版本生成代码。
🌐 The target option specifies which React version the compiler should generate code for.
{
target: '19' // or '18', '17'
}参考
🌐 Reference
target
配置编译输出的 React 版本兼容性。
🌐 Configures the React version compatibility for the compiled output.
类型
🌐 Type
'17' | '18' | '19'默认值
🌐 Default value
'19'
有效值
🌐 Valid values
'19':目标 React 19(默认)。不需要额外的运行时。'18':目标 React 18。需要react-compiler-runtime包。'17':目标 React 17。需要react-compiler-runtime包。
注意事项
🌐 Caveats
- 始终使用字符串值,而不是数字(例如,使用
'17'而不是17) - 不要包含补丁版本(例如,使用
'18'而不是'18.2.0') - React 19 包含内置编译器运行时 API
- React 17 和 18 需要安装
react-compiler-runtime@latest
用法
🌐 Usage
目标版本:React 19(默认)
🌐 Targeting React 19 (default)
对于 React 19,无需特殊配置:
🌐 For React 19, no special configuration is needed:
{
// defaults to target: '19'
}编译器将使用 React 19 的内置运行时 API:
🌐 The compiler will use React 19’s built-in runtime APIs:
// Compiled output uses React 19's native APIs
import { c as _c } from 'react/compiler-runtime';目标平台:React 17 或 18
🌐 Targeting React 17 or 18
对于 React 17 和 React 18 项目,你需要两个步骤:
🌐 For React 17 and React 18 projects, you need two steps:
- 安装运行时包:
npm install react-compiler-runtime@latest- 配置目标:
// For React 18
{
target: '18'
}
// For React 17
{
target: '17'
}编译器将使用两个版本的 polyfill 运行时:
🌐 The compiler will use the polyfill runtime for both versions:
// Compiled output uses the polyfill
import { c as _c } from 'react-compiler-runtime';故障排除
🌐 Troubleshooting
关于缺少编译器运行时的运行时错误
🌐 Runtime errors about missing compiler runtime
如果你看到类似“找不到模块 ‘react/compiler-runtime’”的错误:
🌐 If you see errors like “Cannot find module ‘react/compiler-runtime’“:
-
检查你的 React 版本:
npm why react -
如果使用的是 React 17 或 18,请安装运行时:
npm install react-compiler-runtime@latest -
确保你的目标与你的 React 版本匹配:
{target: '18' // Must match your React major version}
运行时包无法正常工作
🌐 Runtime package not working
确保运行时包是:
🌐 Ensure the runtime package is:
- 安装在你的项目中(而非全局安装)
- 列在你的
package.json依赖中 - 正确版本(
@latest标签) - 不在
devDependencies中(运行时需要它)
检查编译输出
🌐 Checking compiled output
要验证正在使用正确的运行时,请注意不同的导入(builtin 使用 react/compiler-runtime,17/18 使用独立包 react-compiler-runtime):
🌐 To verify the correct runtime is being used, note the different import (react/compiler-runtime for builtin, react-compiler-runtime standalone package for 17/18):
// For React 19 (built-in runtime)
import { c } from 'react/compiler-runtime'
// ^
// For React 17/18 (polyfill runtime)
import { c } from 'react-compiler-runtime'
// ^