本页列出了 React Compiler 中所有可用的配置选项。

¥This page lists all configuration options available in React Compiler.

注意

对于大多数应用,默认选项应该开箱即用。如果你有特殊需求,可以使用这些高级选项。

¥For most apps, the default options should work out of the box. If you have a special need, you can use these advanced options.

// babel.config.js
module.exports = {
plugins: [
[
'babel-plugin-react-compiler', {
// compiler options
}
]
]
};

编译控制

¥Compilation Control

这些选项控制编译器优化的内容以及如何选择要编译的组件和钩子。

¥These options control what the compiler optimizes and how it selects components and hooks to compile.

  • compilationMode 控制选择要编译函数的策略(例如,所有函数、仅注释函数或智能检测)。

    ¥compilationMode controls the strategy for selecting functions to compile (e.g., all functions, only annotated ones, or intelligent detection).

{
compilationMode: 'annotation' // Only compile "use memo" functions
}

版本兼容性

¥Version Compatibility

React 版本配置可确保编译器生成与你的 React 版本兼容的代码。

¥React version configuration ensures the compiler generates code compatible with your React version.

target 指定你正在使用的 React 版本(17、18 或 19)。

¥target specifies which React version you’re using (17, 18, or 19).

// For React 18 projects
{
target: '18' // Also requires react-compiler-runtime package
}

错误处理

¥Error Handling

这些选项控制编译器如何响应不遵循 React 的规则 的代码。

¥These options control how the compiler responds to code that doesn’t follow the Rules of React.

panicThreshold 决定是否使构建失败或跳过有问题的组件。

¥panicThreshold determines whether to fail the build or skip problematic components.

// Recommended for production
{
panicThreshold: 'none' // Skip components with errors instead of failing the build
}

调试

¥Debugging

日志和分析选项可帮助你了解编译器正在执行的操作。

¥Logging and analysis options help you understand what the compiler is doing.

logger 为编译事件提供自定义日志记录。

¥logger provides custom logging for compilation events.

{
logger: {
logEvent(filename, event) {
if (event.kind === 'CompileSuccess') {
console.log('Compiled:', filename);
}
}
}
}

功能标志

¥Feature Flags

条件编译允许你控制何时使用优化代码。

¥Conditional compilation lets you control when optimized code is used.

gating 启用运行时功能标志,用于 A/B 测试或逐步推出。

¥gating enables runtime feature flags for A/B testing or gradual rollouts.

{
gating: {
source: 'my-feature-flags',
importSpecifierName: 'isCompilerEnabled'
}
}

常见配置模式

¥Common Configuration Patterns

默认配置

¥Default configuration

对于大多数 React 19 应用,编译器无需配置即可运行:

¥For most React 19 applications, the compiler works without configuration:

// babel.config.js
module.exports = {
plugins: [
'babel-plugin-react-compiler'
]
};

React 17/18 项目

¥React 17/18 projects

旧版本的 React 需要运行时包和目标配置:

¥Older React versions need the runtime package and target configuration:

npm install react-compiler-runtime@rc
{
target: '18' // or '17'
}

增量采用

¥Incremental adoption

从特定目录开始,然后逐步扩展:

¥Start with specific directories and expand gradually:

{
compilationMode: 'annotation' // Only compile "use memo" functions
}