gating 选项启用条件编译,允许你控制在运行时何时使用优化代码。

¥The gating option enables conditional compilation, allowing you to control when optimized code is used at runtime.

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

参考

¥Reference

gating

配置编译函数的运行时功能标志门控。

¥Configures runtime feature flag gating for compiled functions.

类型

¥Type

{
source: string;
importSpecifierName: string;
} | null

默认值

¥Default value

null

属性

¥Properties

  • source:要从中导入功能标志的模块路径

    ¥**source**: Module path to import the feature flag from

  • importSpecifierName:要导入的导出函数的名称

    ¥**importSpecifierName**: Name of the exported function to import

注意事项

¥Caveats

  • 门控函数必须返回布尔值

    ¥The gating function must return a boolean

  • 编译版本和原始版本都会增加 bundle 的大小

    ¥Both compiled and original versions increase bundle size

  • 导入操作会添加到每个包含已编译函数的文件中

    ¥The import is added to every file with compiled functions


用法

¥Usage

基本功能开关设置

¥Basic feature flag setup

  1. 创建功能开关模块:

    ¥Create a feature flag module:

// src/utils/feature-flags.js
export function shouldUseCompiler() {
// your logic here
return getFeatureFlag('react-compiler-enabled');
}
  1. 配置编译器:

    ¥Configure the compiler:

{
gating: {
source: './src/utils/feature-flags',
importSpecifierName: 'shouldUseCompiler'
}
}
  1. 编译器生成门控代码:

    ¥The compiler generates gated code:

// Input
function Button(props) {
return <button>{props.label}</button>;
}

// Output (simplified)
import { shouldUseCompiler } from './src/utils/feature-flags';

const Button = shouldUseCompiler()
? function Button_optimized(props) { /* compiled version */ }
: function Button_original(props) { /* original version */ };

请注意,门控函数在模块运行时会执行一次,因此一旦 JS 包被解析并执行,组件的选择就会在浏览器会话的剩余时间内保持不变。

¥Note that the gating function is evaluated once at module time, so once the JS bundle has been parsed and evaluated the choice of component stays static for the rest of the browser session.


故障排除

¥Troubleshooting

功能标志不起作用

¥Feature flag not working

验证你的 flag 模块是否导出了正确的函数:

¥Verify your flag module exports the correct function:

// ❌ Wrong: Default export
export default function shouldUseCompiler() {
return true;
}

// ✅ Correct: Named export matching importSpecifierName
export function shouldUseCompiler() {
return true;
}

导入错误

¥Import errors

确保源路径正确:

¥Ensure the source path is correct:

// ❌ Wrong: Relative to babel.config.js
{
source: './src/flags',
importSpecifierName: 'flag'
}

// ✅ Correct: Module resolution path
{
source: '@myapp/feature-flags',
importSpecifierName: 'flag'
}

// ✅ Also correct: Absolute path from project root
{
source: './src/utils/flags',
importSpecifierName: 'flag'
}