React 编译器

编辑

学习如何在 Expo 应用中启用和使用 React 编译器。


新的 React 编译器 自动记忆组件和钩子,以实现细粒度的反应性。这可以显著提高您应用的性能。您可以通过以下说明在您的应用中启用它。

启用 React 编译器

1

检查您的项目与 React 编译器的兼容性

Terminal
npx react-compiler-healthcheck@latest

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

2

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

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

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

3

在您的应用配置文件中启用 React 编译器实验:

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

启用 linter

将来,以下所有步骤将由 Expo CLI 自动化。

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

1

运行 npx expo lint 以确保 ESLint 在您的应用中设置正确,然后安装 React 编译器的 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 编译器:

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 打包器以应用更改:

Terminal
npx expo start --clear

2

使用 "use no memo" 指令选择不使用特定组件或文件的 React 编译器。

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

使用

要更好地理解 React 编译器的工作原理,请查看 React Playground

改进主要是自动的。您可以删除 useCallbackuseMemoReact.memo 的实例,转而使用自动记忆。类组件不会被优化。相反,请迁移到函数组件。

Expo 的 React 编译器实现仅在应用代码上运行(不包括节点模块),并且只在为客户端打包时运行(在服务器渲染中禁用)。

配置

您可以通过使用 Babel 配置中的 react-compiler 对象向 React 编译器 Babel 插件传递附加设置:

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