React 编译器

编辑页面

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


For the complete documentation index, see llms.txt. Use this Use this file to discover all available pages.

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

启用 React Compiler

1

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

Terminal
npx react-compiler-healthcheck@latest

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

2

在你的项目中安装 babel-plugin-react-compiler 和 React compiler runtime:

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

Terminal
npx expo install babel-plugin-react-compiler@beta
Terminal
npx expo install babel-plugin-react-compiler@beta react-compiler-runtime@beta

3

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

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

启用 linter

未来,以下所有步骤都将由 Expo CLI 自动完成。

此外,你应该使用 ESLint 插件持续在你的项目中强制执行 React 规则。

1

运行 npx expo lint 以确保你的应用已设置好 ESLint,然后安装 React Compiler 的 ESLint 插件:

Terminal
npx expo install eslint-plugin-react-compiler -- -D

2

更新你的 ESLint 配置 以包含该插件:

.eslintrc.js
// https://docs.expo.dev/guides/using-eslint/ const { defineConfig } = require('eslint/config'); const expoConfig = require('eslint-config-expo/flat'); const reactCompiler = require('eslint-plugin-react-compiler'); module.exports = defineConfig([ expoConfig, reactCompiler.configs.recommended, { ignores: ['dist/*'], }, ]);

渐进式采用

你可以使用以下几种策略在你的应用中逐步采用 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 Compiler 中的文件名。 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>; }

使用

要更好地理解 React Compiler 的工作方式,请查看 React Playground

改进主要是自动完成的。你可以移除 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 的设置... }, }, }, ], ], }; };