编译库

本指南帮助库作者了解如何使用 React 编译器将优化后的库代码交付给用户。

为什么要发布编译后的代码?

🌐 Why Ship Compiled Code?

作为库的作者,你可以在发布到 npm 之前编译你的库代码。这提供了几个好处:

🌐 As a library author, you can compile your library code before publishing to npm. This provides several benefits:

  • 为所有用户提升性能 - 即使你的库用户尚未使用 React 编译器,也能获得优化的代码
  • 用户无需配置 - 优化功能开箱即用
  • 一致的行为 - 所有用户无论其构建环境如何,都将获得相同的优化版本

设置编译

🌐 Setting Up Compilation

将 React Compiler 添加到你的库的构建过程中:

🌐 Add React Compiler to your library’s build process:

Terminal
npm install -D babel-plugin-react-compiler@latest

配置你的构建工具以编译你的库。例如,使用 Babel:

🌐 Configure your build tool to compile your library. For example, with Babel:

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

向后兼容性

🌐 Backwards Compatibility

如果你的库支持 React 19 以下的版本,则需要进行额外配置:

🌐 If your library supports React versions below 19, you’ll need additional configuration:

1. 安装运行时包

🌐 1. Install the runtime package

我们建议安装 react-compiler-runtime 作为直接依赖:

🌐 We recommend installing react-compiler-runtime as a direct dependency:

Terminal
npm install react-compiler-runtime@latest
{
"dependencies": {
"react-compiler-runtime": "^1.0.0"
},
"peerDependencies": {
"react": "^17.0.0 || ^18.0.0 || ^19.0.0"
}
}

2. 配置目标版本

🌐 2. Configure the target version

设置你的库支持的最低 React 版本:

🌐 Set the minimum React version your library supports:

{
target: '17', // Minimum supported React version
}

测试策略

🌐 Testing Strategy

在编译与未编译的情况下测试你的库,以确保兼容性。将现有的测试套件运行在编译后的代码上,同时创建一个绕过编译器的单独测试配置。这有助于发现编译过程中可能出现的任何问题,并确保你的库在各种情况下都能正常工作。

🌐 Test your library both with and without compilation to ensure compatibility. Run your existing test suite against the compiled code, and also create a separate test configuration that bypasses the compiler. This helps catch any issues that might arise from the compilation process and ensures your library works correctly in all scenarios.

故障排除

🌐 Troubleshooting

库不支持旧版 React 版本

🌐 Library doesn’t work with older React versions

如果你编译的库在 React 17 或 18 中抛出错误:

🌐 If your compiled library throws errors in React 17 or 18:

  1. 确认你已将 react-compiler-runtime 安装为依赖
  2. 检查你的 target 配置是否与你支持的最低 React 版本匹配
  3. 确保运行时包包含在你发布的 bundle 中

与其他 Babel 插件编译冲突

🌐 Compilation conflicts with other Babel plugins

某些 Babel 插件可能与 React 编译器冲突:

🌐 Some Babel plugins may conflict with React Compiler:

  1. babel-plugin-react-compiler 放在你的插件列表的前面
  2. 禁用其他插件中冲突的优化
  3. 彻底测试你的构建输出

未找到运行时模块

🌐 Runtime module not found

如果用户看到“无法找到模块 ‘react-compiler-runtime’”:

🌐 If users see “Cannot find module ‘react-compiler-runtime’“:

  1. 确保运行时列在 dependencies,而不是 devDependencies
  2. 检查你的打包器是否在输出中包含运行时
  3. 验证软件包是否已随库一起发布到 npm

下一步

🌐 Next Steps