跳到内容

reactCompiler

此功能目前处于实验阶段,可能会有变动,不建议在生产环境中使用。请试用并分享您在 GitHub 上的反馈。

Next.js 15 引入了对 React Compiler 的支持。该编译器通过自动优化组件渲染来提高性能。这减少了开发者必须通过诸如 useMemouseCallback 等 API 进行手动记忆化的工作量。

要使用它,请升级到 Next.js 15,安装 babel-plugin-react-compiler

终端
npm install babel-plugin-react-compiler

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

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

注意: React Compiler 目前只能通过 Babel 插件在 Next.js 中使用。这将选择退出 Next.js 默认的 基于 Rust 的编译器,这可能会导致更慢的构建时间。我们正在努力支持将 React Compiler 作为我们的默认编译器。

注解

您可以配置编译器以 “选择加入” 模式运行,如下所示

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

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

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

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