React 编译器

本页将向你介绍新的实验性 React 编译器以及如何成功尝试它。

¥This page will give you an introduction to the new experimental React Compiler and how to try it out successfully.

开发中

These docs are still a work in progress. More documentation is available in the React Compiler Working Group repo, and will be upstreamed into these docs when they are more stable.

你将学习到

  • 编译器入门

    ¥Getting started with the compiler

  • 安装编译器和 eslint 插件

    ¥Installing the compiler and eslint plugin

  • 故障排除

    ¥Troubleshooting

注意

React Compiler 是一个新的实验性编译器,我们将其开源以获取社区的早期反馈。它仍然有一些粗糙的地方,还没有完全准备好投入生产。

¥React Compiler is a new experimental compiler that we’ve open sourced to get early feedback from the community. It still has rough edges and is not yet fully ready for production.

React Compiler 需要 React 19 RC。如果你无法升级到 React 19,你可以尝试使用 工作组 中描述的缓存功能的用户空间实现。但是,请注意,不建议这样做,你应该在可能时升级到 React 19。

¥React Compiler requires React 19 RC. If you are unable to upgrade to React 19, you may try a userspace implementation of the cache function as described in the Working Group. However, please note that this is not recommended and you should upgrade to React 19 when possible.

React Compiler 是一个新的实验性编译器,我们将其开源以获取社区的早期反馈。它是一个仅构建时的工具,可以自动优化你的 React 应用。它使用纯 JavaScript,并理解 React 的规则,因此你无需重写任何代码即可使用它。

¥React Compiler is a new experimental compiler that we’ve open sourced to get early feedback from the community. It is a build-time only tool that automatically optimizes your React app. It works with plain JavaScript, and understands the Rules of React, so you don’t need to rewrite any code to use it.

编译器还包括一个 eslint 插件,可以在编辑器中直接显示编译器的分析结果。该插件独立于编译器运行,即使你没有在应用中使用编译器也可以使用。我们建议所有 React 开发者使用此 eslint 插件来帮助提高代码库的质量。

¥The compiler also includes an eslint plugin that surfaces the analysis from the compiler right in your editor. The plugin runs independently of the compiler and can be used even if you aren’t using the compiler in your app. We recommend all React developers to use this eslint plugin to help improve the quality of your codebase.

编译器做什么?

¥What does the compiler do?

为了优化应用,React Compiler 会自动记忆你的代码。你今天可能熟悉通过 useMemouseCallbackReact.memo 等 API 进行记忆化。使用这些 API,你可以告诉 React,如果应用的某些部分的输入没有改变,则不需要重新计算,从而减少更新工作。虽然功能强大,但很容易忘记应用记忆或错误地应用它们。这可能会导致更新效率低下,因为 React 必须检查 UI 中没有任何有意义更改的部分。

¥In order to optimize applications, React Compiler automatically memoizes your code. You may be familiar today with memoization through APIs such as useMemo, useCallback, and React.memo. With these APIs you can tell React that certain parts of your application don’t need to recompute if their inputs haven’t changed, reducing work on updates. While powerful, it’s easy to forget to apply memoization or apply them incorrectly. This can lead to inefficient updates as React has to check parts of your UI that don’t have any meaningful changes.

编译器使用其对 JavaScript 和 React 规则的了解来自动记忆组件和钩子内的值或值组。如果它检测到规则的破坏,它将自动跳过这些组件或钩子,并继续安全地编译其他代码。

¥The compiler uses its knowledge of JavaScript and React’s rules to automatically memoize values or groups of values within your components and hooks. If it detects breakages of the rules, it will automatically skip over just those components or hooks, and continue safely compiling other code.

如果你的代码库已经很好地进行了记忆,你可能不会期望编译器会带来重大的性能改进。然而,在实践中,手动记住导致性能问题的正确依赖是很棘手的。

¥If your codebase is already very well-memoized, you might not expect to see major performance improvements with the compiler. However, in practice memoizing the correct dependencies that cause performance issues is tricky to get right by hand.

深入研究

React Compiler 添加了什么样的记忆?

¥What kind of memoization does React Compiler add?

React Compiler 的初始版本主要侧重于提高更新性能(重新渲染现有组件),因此它专注于以下两个用例:

¥The initial release of React Compiler is primarily focused on improving update performance (re-rendering existing components), so it focuses on these two use cases:

  1. 跳过组件的级联重新渲染

    ¥Skipping cascading re-rendering of components

    • 重新渲染 <Parent /> 会导致其组件树中的许多组件重新渲染,即使只有 <Parent /> 发生了变化

      ¥Re-rendering <Parent /> causes many components in its component tree to re-render, even though only <Parent /> has changed

  2. 跳过 React 外部的昂贵计算

    ¥Skipping expensive calculations from outside of React

    • 例如,在需要该数据的组件或钩子内部调用 expensivelyProcessAReallyLargeArrayOfObjects()

      ¥For example, calling expensivelyProcessAReallyLargeArrayOfObjects() inside of your component or hook that needs that data

优化重新渲染

¥Optimizing Re-renders

React 可让你根据其当前状态(更具体地说:其属性、状态和上下文)来表达你的 UI。在当前实现中,当组件的状态发生变化时,React 将重新渲染该组件及其所有子组件 - 除非你已使用 useMemo()useCallback()React.memo() 应用了某种形式的手动记忆。例如,在以下示例中,每当 <FriendList> 的状态发生变化时,<MessageButton> 都会重新渲染:

¥React lets you express your UI as a function of their current state (more concretely: their props, state, and context). In its current implementation, when a component’s state changes, React will re-render that component and all of its children — unless you have applied some form of manual memoization with useMemo(), useCallback(), or React.memo(). For example, in the following example, <MessageButton> will re-render whenever <FriendList>’s state changes:

function FriendList({ friends }) {
const onlineCount = useFriendOnlineCount();
if (friends.length === 0) {
return <NoFriends />;
}
return (
<div>
<span>{onlineCount} online</span>
{friends.map((friend) => (
<FriendListCard key={friend.id} friend={friend} />
))}
<MessageButton />
</div>
);
}

请参阅 React Compiler Playground 中的此示例

¥See this example in the React Compiler Playground

React Compiler 自动应用相当于手动记忆的功能,确保只有应用的相关部分在状态更改时重新渲染,这有时被称为 “细粒度反应性”。在上面的例子中,React Compiler 确定即使 friends 发生变化,<FriendListCard /> 的返回值也可以重用,并且可以避免重新创建此 JSX 并避免在计数发生变化时重新渲染 <MessageButton>

¥React Compiler automatically applies the equivalent of manual memoization, ensuring that only the relevant parts of an app re-render as state changes, which is sometimes referred to as “fine-grained reactivity”. In the above example, React Compiler determines that the return value of <FriendListCard /> can be reused even as friends changes, and can avoid recreating this JSX and avoid re-rendering <MessageButton> as the count changes.

昂贵的计算也会被记忆化

¥Expensive calculations also get memoized

编译器还可以自动记忆渲染期间使用的昂贵计算:

¥The compiler can also automatically memoize for expensive calculations used during rendering:

// **Not** memoized by React Compiler, since this is not a component or hook
function expensivelyProcessAReallyLargeArrayOfObjects() { /* ... */ }

// Memoized by React Compiler since this is a component
function TableContainer({ items }) {
// This function call would be memoized:
const data = expensivelyProcessAReallyLargeArrayOfObjects(items);
// ...
}

请参阅 React Compiler Playground 中的此示例

¥See this example in the React Compiler Playground

但是,如果 expensivelyProcessAReallyLargeArrayOfObjects 确实是一个昂贵的函数,你可能需要考虑在 React 之外实现自己的记忆,因为:

¥However, if expensivelyProcessAReallyLargeArrayOfObjects is truly an expensive function, you may want to consider implementing its own memoization outside of React, because:

  • React Compiler 仅记忆 React 组件和钩子,而不是每个函数

    ¥React Compiler only memoizes React components and hooks, not every function

  • React Compiler 的记忆不会在多个组件或钩子之间共享

    ¥React Compiler’s memoization is not shared across multiple components or hooks

因此,如果 expensivelyProcessAReallyLargeArrayOfObjects 在许多不同的组件中使用,即使传递了相同的项目,也会重复运行该昂贵的计算。我们建议先使用 profiling,看看它是否真的那么昂贵,然后再使代码变得更复杂。

¥So if expensivelyProcessAReallyLargeArrayOfObjects was used in many different components, even if the same exact items were passed down, that expensive calculation would be run repeatedly. We recommend profiling first to see if it really is that expensive before making code more complicated.

编译器假设什么?

¥What does the compiler assume?

React Compiler 假设你的代码:

¥React Compiler assumes that your code:

  1. 是有效的、语义化的 JavaScript

    ¥Is valid, semantic JavaScript

  2. 在访问可空/可选值和属性之前,测试它们是否已定义(例如,如果使用 TypeScript,则通过启用 strictNullChecks),即 if (object.nullableProperty) { object.nullableProperty.foo } 或使用可选链 object.nullableProperty?.foo

    ¥Tests that nullable/optional values and properties are defined before accessing them (for example, by enabling strictNullChecks if using TypeScript), i.e., if (object.nullableProperty) { object.nullableProperty.foo } or with optional-chaining object.nullableProperty?.foo

  3. 遵循 React 的规则

    ¥Follows the Rules of React

React Compiler 可以静态验证 React 的许多规则,并在检测到错误时安全地跳过编译。要查看错误,我们还建议安装 eslint-plugin-react-compiler

¥React Compiler can verify many of the Rules of React statically, and will safely skip compilation when it detects an error. To see the errors we recommend also installing eslint-plugin-react-compiler.

我应该尝试一下编译器吗?

¥Should I try out the compiler?

请注意,该编译器仍处于实验阶段,并且有许多粗糙的地方。虽然它已在 Meta 等公司的生产中使用,但将编译器推出到你的应用的生产中将取决于你的代码库的运行状况以及你遵循 React 的规则 的程度。

¥Please note that the compiler is still experimental and has many rough edges. While it has been used in production at companies like Meta, rolling out the compiler to production for your app will depend on the health of your codebase and how well you’ve followed the Rules of React.

你现在不必急于使用编译器。可以等到它达到稳定版本后再采用它。不过,我们非常感谢你在应用中进行小实验,以便你可以向我们提供帮助,以帮助改进编译器。

¥You don’t have to rush into using the compiler now. It’s okay to wait until it reaches a stable release before adopting it. However, we do appreciate trying it out in small experiments in your apps so that you can provide feedback to us to help make the compiler better.

入门

¥Getting Started

除了这些文档之外,我们建议检查 React 编译器工作组 以获取有关编译器的其他信息和讨论。

¥In addition to these docs, we recommend checking the React Compiler Working Group for additional information and discussion about the compiler.

检查兼容性

¥Checking compatibility

在安装编译器之前,你可以首先检查你的代码库是否兼容:

¥Prior to installing the compiler, you can first check to see if your codebase is compatible:

Terminal
npx react-compiler-healthcheck@experimental

该脚本将:

¥This script will:

  • 检查有多少组件可以成功优化:越高越好

    ¥Check how many components can be successfully optimized: higher is better

  • 检查 <StrictMode> 的使用情况:启用并关注此功能意味着 React 的规则 被关注的机会更高

    ¥Check for <StrictMode> usage: having this enabled and followed means a higher chance that the Rules of React are followed

  • 检查不兼容的库使用:与编译器不兼容的已知库

    ¥Check for incompatible library usage: known libraries that are incompatible with the compiler

举个例子:

¥As an example:

Terminal
Successfully compiled 8 out of 9 components. StrictMode usage not found. Found no usage of incompatible libraries.

安装 eslint-plugin-react-compiler

¥Installing eslint-plugin-react-compiler

React Compiler 还支持 eslint 插件。eslint 插件可以独立于编译器使用,这意味着即使你不使用编译器也可以使用 eslint 插件。

¥React Compiler also powers an eslint plugin. The eslint plugin can be used independently of the compiler, meaning you can use the eslint plugin even if you don’t use the compiler.

Terminal
npm install eslint-plugin-react-compiler@experimental

然后,将其添加到你的 eslint 配置中:

¥Then, add it to your eslint config:

module.exports = {
plugins: [
'eslint-plugin-react-compiler',
],
rules: {
'react-compiler/react-compiler': "error",
},
}

eslint 插件将在你的编辑器中显示任何违反 React 规则的行为。当它这样做时,意味着编译器跳过了优化该组件或钩子。这完全没问题,编译器可以恢复并继续优化代码库中的其他组件。

¥The eslint plugin will display any violations of the rules of React in your editor. When it does this, it means that the compiler has skipped over optimizing that component or hook. This is perfectly okay, and the compiler can recover and continue optimizing other components in your codebase.

你不必立即修复所有 eslint 违规行为。你可以按照自己的节奏解决这些问题,以增加要优化的组件和钩子的数量,但在使用编译器之前不需要修复所有问题。

¥You don’t have to fix all eslint violations straight away. You can address them at your own pace to increase the amount of components and hooks being optimized, but it is not required to fix everything before you can use the compiler.

将编译器推出到你的代码库

¥Rolling out the compiler to your codebase

现有项目

¥Existing projects

该编译器旨在编译遵循 React 的规则 的功能组件和钩子。它还可以通过退出(跳过)这些组件或钩子来处理违反这些规则的代码。然而,由于 JavaScript 的灵活性,编译器无法捕获所有可能的违规行为,并且可能会出现误报:也就是说,编译器可能会意外编译一个违反 React 规则的组件/钩子,从而导致未定义的行为。

¥The compiler is designed to compile functional components and hooks that follow the Rules of React. It can also handle code that breaks those rules by bailing out (skipping over) those components or hooks. However, due to the flexible nature of JavaScript, the compiler cannot catch every possible violation and may compile with false negatives: that is, the compiler may accidentally compile a component/hook that breaks the Rules of React which can lead to undefined behavior.

因此,为了在现有项目中成功采用编译器,我们建议首先在产品代码中的一个小目录中运行它。你可以通过将编译器配置为仅在一组特定目录上运行来实现此目的:

¥For this reason, to adopt the compiler successfully on existing projects, we recommend running it on a small directory in your product code first. You can do this by configuring the compiler to only run on a specific set of directories:

const ReactCompilerConfig = {
sources: (filename) => {
return filename.indexOf('src/path/to/dir') !== -1;
},
};

在极少数情况下,你还可以使用 compilationMode: "annotation" 选项将编译器配置为在 “opt-in” 模式下运行。这使得编译器只会编译用 "use memo" 指令注释的组件和钩子。请注意,annotation 模式是一种临时模式,旨在帮助早期采用者,我们不打算长期使用 "use memo" 指令。

¥In rare cases, you can also configure the compiler to run in “opt-in” mode using the compilationMode: "annotation" option. This makes it so the compiler will only compile components and hooks annotated with a "use memo" directive. Please note that the annotation mode is a temporary one to aid early adopters, and that we don’t intend for the "use memo" directive to be used for the long term.

const ReactCompilerConfig = {
compilationMode: "annotation",
};

// src/app.jsx
export default function App() {
"use memo";
// ...
}

当你对推出编译器更有信心时,你也可以将覆盖范围扩大到其他目录,并慢慢将其推广到整个应用。

¥When you have more confidence with rolling out the compiler, you can expand coverage to other directories as well and slowly roll it out to your whole app.

新项目

¥New projects

如果你要开始一个新项目,你可以在整个代码库上启用编译器,这是默认行为。

¥If you’re starting a new project, you can enable the compiler on your entire codebase, which is the default behavior.

用法

¥Usage

Babel

Terminal
npm install babel-plugin-react-compiler@experimental

编译器包含一个 Babel 插件,你可以在构建管道中使用该插件来运行编译器。

¥The compiler includes a Babel plugin which you can use in your build pipeline to run the compiler.

安装后,将其添加到 Babel 配置中。请注意,编译器首先在管道中运行至关重要:

¥After installing, add it to your Babel config. Please note that it’s critical that the compiler run first in the pipeline:

// babel.config.js
const ReactCompilerConfig = { /* ... */ };

module.exports = function () {
return {
plugins: [
['babel-plugin-react-compiler', ReactCompilerConfig], // must run first!
// ...
],
};
};

babel-plugin-react-compiler 应该先于其他 Babel 插件运行,因为编译器需要输入源信息进行声音分析。

¥babel-plugin-react-compiler should run first before other Babel plugins as the compiler requires the input source information for sound analysis.

Vite

如果你使用 Vite,可以将插件添加到 vite-plugin-react 中:

¥If you use Vite, you can add the plugin to vite-plugin-react:

// vite.config.js
const ReactCompilerConfig = { /* ... */ };

export default defineConfig(() => {
return {
plugins: [
react({
babel: {
plugins: [
["babel-plugin-react-compiler", ReactCompilerConfig],
],
},
}),
],
// ...
};
});

Next.js

Next.js 有一个实验性配置来启用 React 编译器。它会自动确保 Babel 设置为 babel-plugin-react-compiler

¥Next.js has an experimental configuration to enable the React Compiler. It automatically ensures Babel is set up with babel-plugin-react-compiler.

  • 安装 Next.js canary,它使用 React 19 Release Candidate

    ¥Install Next.js canary, which uses React 19 Release Candidate

  • 安装 babel-plugin-react-compiler

    ¥Install babel-plugin-react-compiler

Terminal
npm install next@canary babel-plugin-react-compiler@experimental

然后在 next.config.js 中配置实验选项:

¥Then configure the experimental option in next.config.js:

// next.config.js
/** @type {import('next').NextConfig} */
const nextConfig = {
experimental: {
reactCompiler: true,
},
};

module.exports = nextConfig;

使用实验选项可确保在以下方面支持 React 编译器:

¥Using the experimental option ensures support for the React Compiler in:

  • 应用路由

    ¥App Router

  • 页面路由

    ¥Pages Router

  • 网络包(默认)

    ¥Webpack (default)

  • Turbopack(通过 --turbo 选择加入)

    ¥Turbopack (opt-in through --turbo)

Remix

安装 vite-plugin-babel,并添加编译器的 Babel 插件:

¥Install vite-plugin-babel, and add the compiler’s Babel plugin to it:

Terminal
npm install vite-plugin-babel
// vite.config.js
import babel from "vite-plugin-babel";

const ReactCompilerConfig = { /* ... */ };

export default defineConfig({
plugins: [
remix({ /* ... */}),
babel({
filter: /\.[jt]sx?$/,
babelConfig: {
presets: ["@babel/preset-typescript"], // if you use TypeScript
plugins: [
["babel-plugin-react-compiler", ReactCompilerConfig],
],
},
}),
],
});

Webpack

你可以为 React Compiler 创建自己的加载器,如下所示:

¥You can create your own loader for React Compiler, like so:

const ReactCompilerConfig = { /* ... */ };
const BabelPluginReactCompiler = require('babel-plugin-react-compiler');

function reactCompilerLoader(sourceCode, sourceMap) {
// ...
const result = transformSync(sourceCode, {
// ...
plugins: [
[BabelPluginReactCompiler, ReactCompilerConfig],
],
// ...
});

if (result === null) {
this.callback(
Error(
`Failed to transform "${options.filename}"`
)
);
return;
}

this.callback(
null,
result.code,
result.map === null ? undefined : result.map
);
}

module.exports = reactCompilerLoader;

Expo

请参阅 Expo 的文档 以在 Expo 应用中启用和使用 React 编译器。

¥Please refer to Expo’s docs to enable and use the React Compiler in Expo apps.

Metro (React Native)

React Native 通过 Metro 使用 Babel,因此请参阅 与 Babel 一起使用 部分以获取安装说明。

¥React Native uses Babel via Metro, so refer to the Usage with Babel section for installation instructions.

Rspack

请参阅 Rspack 的文档 以在 Rspack 应用中启用和使用 React 编译器。

¥Please refer to Rspack’s docs to enable and use the React Compiler in Rspack apps.

Rsbuild

请参阅 Rsbuild 的文档 以在 Rsbuild 应用中启用和使用 React 编译器。

¥Please refer to Rsbuild’s docs to enable and use the React Compiler in Rsbuild apps.

故障排除

¥Troubleshooting

要报告问题,请首先在 React 编译器在线运行 上创建一个最小的重现并将其包含在你的错误报告中。你可以在 facebook/react 存储库中打开问题。

¥To report issues, please first create a minimal repro on the React Compiler Playground and include it in your bug report. You can open issues in the facebook/react repo.

你还可以通过申请成为成员来在 React 编译器工作组中提供反馈。请参阅 有关加入的更多详细信息,请参阅自述文件

¥You can also provide feedback in the React Compiler Working Group by applying to be a member. Please see the README for more details on joining.

(0 , _c) is not a function 错误

¥(0 , _c) is not a function error

如果你没有使用 React 19 RC 及更高版本,就会发生这种情况。要解决此问题,请先执行 将你的应用升级到 React 19 RC

¥This occurs if you are not using React 19 RC and up. To fix this, upgrade your app to React 19 RC first.

如果你无法升级到 React 19,你可以尝试使用 工作组 中描述的缓存功能的用户空间实现。但是,请注意,不建议这样做,你应该在可能时升级到 React 19。

¥If you are unable to upgrade to React 19, you may try a userspace implementation of the cache function as described in the Working Group. However, please note that this is not recommended and you should upgrade to React 19 when possible.

我如何知道我的组件已经优化?

¥How do I know my components have been optimized?

React Devtools (v5.0+) 内置了对 React Compiler 的支持,并将在编译器已优化的组件旁边显示 “备忘录 ✨” 徽章。

¥React Devtools (v5.0+) has built-in support for React Compiler and will display a “Memo ✨” badge next to components that have been optimized by the compiler.

编译后某些东西不起作用

¥Something is not working after compilation

如果你安装了 eslint-plugin-react-compiler,编译器将在你的编辑器中显示任何违反 React 规则的行为。当它这样做时,意味着编译器跳过了优化该组件或钩子。这完全没问题,编译器可以恢复并继续优化代码库中的其他组件。你不必立即修复所有 eslint 违规行为。你可以按照自己的节奏解决这些问题,以增加要优化的组件和钩子的数量。

¥If you have eslint-plugin-react-compiler installed, the compiler will display any violations of the rules of React in your editor. When it does this, it means that the compiler has skipped over optimizing that component or hook. This is perfectly okay, and the compiler can recover and continue optimizing other components in your codebase. You don’t have to fix all eslint violations straight away. You can address them at your own pace to increase the amount of components and hooks being optimized.

然而,由于 JavaScript 的灵活性和动态性,不可能全面检测所有情况。在这些情况下可能会出现错误和未定义的行为,例如无限循环。

¥Due to the flexible and dynamic nature of JavaScript however, it’s not possible to comprehensively detect all cases. Bugs and undefined behavior such as infinite loops may occur in those cases.

如果你的应用在编译后无法正常工作,并且你没有看到任何 eslint 错误,则编译器可能错误地编译了你的代码。为了确认这一点,请尝试通过积极选择退出你认为可能与 "use no memo" 指令 相关的任何组件或钩子来解决问题。

¥If your app doesn’t work properly after compilation and you aren’t seeing any eslint errors, the compiler may be incorrectly compiling your code. To confirm this, try to make the issue go away by aggressively opting out any component or hook you think might be related via the "use no memo" directive.

function SuspiciousComponent() {
"use no memo"; // opts out this component from being compiled by React Compiler
// ...
}

注意

"use no memo"

"use no memo" 是一个临时的逃生舱,可让你选择退出 React Compiler 编译的组件和钩子。此指令并不打算像 "use client" 那样长期存在。

¥"use no memo" is a temporary escape hatch that lets you opt-out components and hooks from being compiled by the React Compiler. This directive is not meant to be long lived the same way as eg "use client" is.

除非绝对必要,否则不建议使用此指令。一旦你选择退出组件或钩子,它将永远被选择退出,直到删除该指令。这意味着即使你修复了代码,除非你删除该指令,否则编译器仍会跳过编译它。

¥It is not recommended to reach for this directive unless it’s strictly necessary. Once you opt-out a component or hook, it is opted-out forever until the directive is removed. This means that even if you fix the code, the compiler will still skip over compiling it unless you remove the directive.

当你使错误消失时,请确认删除 opt out 指令会使问题再次出现。然后使用 React 编译器在线运行 与我们分享错误报告(你可以尝试将其缩小为一个小型再现,或者如果它是开源代码,你也可以粘贴整个源代码),以便我们识别并帮助解决问题。

¥When you make the error go away, confirm that removing the opt out directive makes the issue come back. Then share a bug report with us (you can try to reduce it to a small repro, or if it’s open source code you can also just paste the entire source) using the React Compiler Playground so we can identify and help fix the issue.

其他事宜

¥Other issues

请参阅 https://github.com/reactwg/react-compiler/discussions/7

¥Please see https://github.com/reactwg/react-compiler/discussions/7.


React 中文网 - 粤ICP备13048890号