跳到内容

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'
  // ...
}

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