跳到内容

reactCompiler

Next.js 支持 React 编译器,这是一个旨在通过自动优化组件渲染来提高性能的工具。它减少了使用 useMemouseCallback 进行手动记忆化的需求。

Next.js 包含一个用 SWC 编写的自定义性能优化功能,它使 React 编译器更高效。Next.js 不会在每个文件上运行编译器,而是分析你的项目,只将 React 编译器应用于相关文件。这避免了不必要的工作,与单独使用 Babel 插件相比,可以实现更快的构建。

工作原理

React 编译器通过 Babel 插件运行。为了保持构建速度,Next.js 使用自定义的 SWC 优化,只将 React 编译器应用于相关文件,例如包含 JSX 或 React Hooks 的文件。

这避免了编译所有内容,并将性能开销降到最低。与默认的基于 Rust 的编译器相比,你可能仍然会看到构建速度略慢,但影响很小且是局部性的。

要使用它,请安装 babel-plugin-react-compiler

终端
npm install babel-plugin-react-compiler

然后,在 next.config.js 中添加 reactCompiler 选项

next.config.ts
import type { NextConfig } from 'next'
 
const nextConfig: NextConfig = {
  reactCompiler: true,
}
 
export default nextConfig

注解

你可以如下配置编译器以“选择加入”模式运行

next.config.ts
import type { NextConfig } from 'next'
 
const nextConfig: NextConfig = {
  reactCompiler: {
    compilationMode: 'annotation',
  },
}
 
export default nextConfig

然后,你可以使用 React 的 "use memo" 指令注解特定的组件或 Hook 来选择加入。

app/page.tsx
export default function Page() {
  'use memo'
  // ...
}

注意:你也可以使用 React 的 "use no memo" 指令来达到相反的效果,即选择退出组件或 Hook。