Compiling Libraries
This guide helps library authors understand how to use React Compiler to ship optimized library code to their users.
- Why Ship Compiled Code?
- Setting Up Compilation
- Backwards Compatibility
- Testing Strategy
- Troubleshooting
- Next Steps
Why Ship Compiled Code?
As a library author, you can compile your library code before publishing to npm. This provides several benefits:
- Performance improvements for all users - Your library users get optimized code even if they aren’t using React Compiler yet
- No configuration required by users - The optimizations work out of the box
- Consistent behavior - All users get the same optimized version regardless of their build setup
Setting Up Compilation
Add React Compiler to your library’s build process:
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
If your library supports React versions below 19, you’ll need additional configuration:
1. Install the runtime package
We recommend installing react-compiler-runtime as a direct dependency:
{
"dependencies": {
"react-compiler-runtime": "^19.1.0-rc.2"
},
"peerDependencies": {
"react": "^17.0.0 || ^18.0.0 || ^19.0.0"
}
}
2. Configure the target version
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
Library doesn’t work with older React versions
If your compiled library throws errors in React 17 or 18:
- Verify you’ve installed
react-compiler-runtime
as a dependency - Check that your
target
configuration matches your minimum supported React version - Ensure the runtime package is included in your published bundle
Compilation conflicts with other Babel plugins
Some Babel plugins may conflict with React Compiler:
- Place
babel-plugin-react-compiler
early in your plugin list - Disable conflicting optimizations in other plugins
- Test your build output thoroughly
Runtime module not found
If users see “Cannot find module ‘react-compiler-runtime’“:
- Ensure the runtime is listed in
dependencies
, notdevDependencies
- Check that your bundler includes the runtime in the output
- Verify the package is published to npm with your library
Next Steps
- Learn about debugging techniques for compiled code
- Check the configuration options for all compiler options
- Explore compilation modes for selective optimization