This documentation is available as Markdown for AI agents and LLMs. See the full Markdown index or append .md to any documentation URL.

React 编译器

编辑页面

了解如何在 Expo 应用中启用和使用 React 编译器。


新的 React 编译器 会自动对组件和 hooks 进行 memoize,从而实现细粒度响应。这可以显著提升你应用的性能。你可以按照下面的说明在你的应用中启用它。

启用 React 编译器

1

检查兼容性 以了解你的项目与 React 编译器的兼容程度。

Terminal
npx react-compiler-healthcheck@latest

这通常会验证你的应用是否遵循了 React 规则

2

在你的项目中安装 babel-plugin-react-compiler 和 React 编译器运行时:

Expo SDK 54 及更高版本会自动配置 Babel。

3

在你的应用配置文件中开启 React Compiler 实验特性:

app.json
{ "expo": { "experiments": { "reactCompiler": true } } }

启用 linter

运行 npx expo lint 来在你的应用中配置 ESLint,然后按照你的 SDK 版本说明继续操作:

React Compiler 的 lint 规则会在 SDK 55 及更高版本中随 eslint-config-expo 默认包含。

如果你之前安装过 eslint-plugin-react-compiler,可以将其卸载,并从你的 ESLint 配置中移除它。

渐进式采用

你可以使用以下几种策略在你的应用中逐步采用 React Compiler:

1

配置 Babel 插件仅在特定文件或组件上运行。为此:

  1. 如果你的项目没有 babel.config.js,请运行 npx expo customize babel.config.js 创建一个。
  2. 将以下配置添加到 babel.config.js 中:
babel.config.js
module.exports = function (api) { api.cache(true); return { presets: [ [ 'babel-preset-expo', { 'react-compiler': { sources: filename => { // 匹配要包含到 React 编译器中的文件名。 return filename.includes('src/path/to/dir'); }, }, }, ], ], }; };

每当你更改 babel.config.js 文件时,都需要重启 Metro bundler 以应用这些更改:

Terminal
npx expo start --clear

2

使用 "use no memo" 指令,让 React Compiler 对特定组件或文件不生效。

function MyComponent() { 'use no memo'; return <Text>Will not be optimized</Text>; }

使用

改进主要是自动完成的。你可以移除 useCallbackuseMemoReact.memo 的使用,改为依赖自动 memoization。类组件不会被优化,应改为迁移到函数组件。

Expo 对 React Compiler 的实现只会在应用代码上运行(不包括 node_modules),并且只在为客户端打包时运行(服务端渲染中禁用)。

配置

你可以通过在 Babel 配置中使用 react-compiler 对象,向 React Compiler Babel 插件传递额外设置:

babel.config.js
module.exports = function (api) { api.cache(true); return { presets: [ [ 'babel-preset-expo', { 'react-compiler': { // 直接传递给 React Compiler Babel 插件。 compilationMode: 'all', panicThreshold: 'all_errors', }, web: { 'react-compiler': { // 仅限 Web 的设置... }, }, }, ], ], }; };