本指南将帮助你在 React 应用中安装和配置 React Compiler。

¥This guide will help you install and configure React Compiler in your React application.

你将学习到

  • 如何安装 React 编译器

    ¥How to install React Compiler

  • 不同构建工具的基本配置

    ¥Basic configuration for different build tools

  • 如何验证你的设置是否正常工作

    ¥How to verify your setup is working

先决条件

¥Prerequisites

React Compiler 旨在与 React 19 完美兼容,但它也支持 React 17 和 18。了解更多关于 React 版本兼容性 的信息。

¥React Compiler is designed to work best with React 19, but it also supports React 17 and 18. Learn more about React version compatibility.

注意

React Compiler 目前处于 RC 阶段。使用 @rc 标签安装以获取最新的候选发布版本。

¥React Compiler is currently in RC. Install it using the @rc tag to get the latest release candidate version.

安装

¥Installation

将 React Compiler 安装为 devDependency

¥Install React Compiler as a devDependency:

Terminal
npm install -D babel-plugin-react-compiler@rc

或使用 Yarn:

¥Or with Yarn:

Terminal
yarn add -D babel-plugin-react-compiler@rc

或使用 pnpm:

¥Or with pnpm:

Terminal
pnpm install -D babel-plugin-react-compiler@rc

基本设置

¥Basic Setup

React Compiler 默认无需任何配置即可运行。但是,如果你需要在特殊情况下进行配置(例如,针对低于 19 的 React 版本),请参考 编译器选项参考

¥React Compiler is designed to work by default without any configuration. However, if you need to configure it in special circumstances (for example, to target React versions below 19), refer to the compiler options reference.

设置过程取决于你的构建工具。React Compiler 包含一个 Babel 插件,可以与你的构建流程集成。

¥The setup process depends on your build tool. React Compiler includes a Babel plugin that integrates with your build pipeline.

易犯错误

React Compiler 必须在 Babel 插件管道中首先运行。编译器需要原始源信息才能进行正确的分析,因此它必须在进行其他转换之前处理你的代码。

¥React Compiler must run first in your Babel plugin pipeline. The compiler needs the original source information for proper analysis, so it must process your code before other transformations.

Babel

创建或更新你的 babel.config.js

¥Create or update your babel.config.js:

module.exports = {
plugins: [
'babel-plugin-react-compiler', // must run first!
// ... other plugins
],
// ... other config
};

Vite

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

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

// vite.config.js
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';

export default defineConfig({
plugins: [
react({
babel: {
plugins: ['babel-plugin-react-compiler'],
},
}),
],
});

或者,如果你更喜欢为 Vite 使用单独的 Babel 插件:

¥Alternatively, if you prefer a separate Babel plugin for Vite:

Terminal
npm install -D vite-plugin-babel
// vite.config.js
import babel from 'vite-plugin-babel';
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';

export default defineConfig({
plugins: [
react(),
babel({
babelConfig: {
plugins: ['babel-plugin-react-compiler'],
},
}),
],
});

Next.js

有关更多信息,请参阅 Next.js 文档

¥Please refer to the Next.js docs for more information.

React Router

安装 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 { defineConfig } from "vite";
import babel from "vite-plugin-babel";
import { reactRouter } from "@react-router/dev/vite";

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

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

Webpack

社区 webpack 加载器是 现在可在此处使用

¥A community webpack loader is now available here.

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.

ESLint 集成

¥ESLint Integration

React Compiler 包含一条 ESLint 规则,可以帮助识别无法优化的代码。当 ESLint 规则报告错误时,这意味着编译器将跳过对该特定组件或钩子的优化。这是安全的:编译器将继续优化代码库的其他部分。你无需立即修复所有违规行为。按照你自己的节奏逐步增加优化组件的数量。

¥React Compiler includes an ESLint rule that helps identify code that can’t be optimized. When the ESLint rule reports an error, it means the compiler will skip optimizing that specific component or hook. This is safe: the compiler will continue optimizing other parts of your codebase. You don’t need to fix all violations immediately. Address them at your own pace to gradually increase the number of optimized components.

安装 ESLint 插件:

¥Install the ESLint plugin:

Terminal
npm install -D eslint-plugin-react-hooks@rc

然后在你的 ESLint 配置中启用编译器规则:

¥Then enable the compiler rule in your ESLint configuration:

// .eslintrc.js
module.exports = {
rules: {
'react-hooks/react-compiler': 'error',
},
};

ESLint 规则将:

¥The ESLint rule will:

  • 识别违反 React 的规则 的行为

    ¥Identify violations of the Rules of React

  • 显示哪些组件无法优化

    ¥Show which components can’t be optimized

  • 提供有助于解决问题的错误消息

    ¥Provide helpful error messages for fixing issues

验证你的设置

¥Verify Your Setup

安装后,验证 React Compiler 是否正常工作。

¥After installation, verify that React Compiler is working correctly.

检查 React DevTools

¥Check React DevTools

React Compiler 优化的组件将在 React DevTools 中显示 “备忘录 ✨” 标记:

¥Components optimized by React Compiler will show a “Memo ✨” badge in React DevTools:

  1. 安装 React 开发者工具 浏览器扩展

    ¥Install the React Developer Tools browser extension

  2. 以开发模式打开你的应用

    ¥Open your app in development mode

  3. 打开 React DevTools

    ¥Open React DevTools

  4. 在组件名称旁边查找 ✨ 表情符号

    ¥Look for the ✨ emoji next to component names

如果编译器正常运行:

¥If the compiler is working:

  • 组件将在 React DevTools 中显示 “备忘录 ✨” 标记

    ¥Components will show a “Memo ✨” badge in React DevTools

  • 昂贵的计算将被自动记忆

    ¥Expensive calculations will be automatically memoized

  • 无需手动 useMemo

    ¥No manual useMemo is required

检查构建输出

¥Check Build Output

你还可以通过检查构建输出来验证编译器是否正在运行。编译后的代码将包含编译器自动添加的自动记忆逻辑。

¥You can also verify the compiler is running by checking your build output. The compiled code will include automatic memoization logic that the compiler adds automatically.

import { c as _c } from "react/compiler-runtime";
export default function MyApp() {
const $ = _c(1);
let t0;
if ($[0] === Symbol.for("react.memo_cache_sentinel")) {
t0 = <div>Hello World</div>;
$[0] = t0;
} else {
t0 = $[0];
}
return t0;
}

故障排除

¥Troubleshooting

禁用特定组件

¥Opting out specific components

如果某个组件在编译后导致问题,你可以使用 "use no memo" 指令暂时将其禁用:

¥If a component is causing issues after compilation, you can temporarily opt it out using the "use no memo" directive:

function ProblematicComponent() {
"use no memo";
// Component code here
}

这会告诉编译器跳过针对此特定组件的优化。你应该修复底层问题,并在解决后删除该指令。

¥This tells the compiler to skip optimization for this specific component. You should fix the underlying issue and remove the directive once resolved.

有关更多故障排除帮助,请参阅 调试指南

¥For more troubleshooting help, see the debugging guide.

下一步

¥Next Steps

现在你已经安装了 React Compiler,请了解更多信息:

¥Now that you have React Compiler installed, learn more about: