reactCompiler

Next.js 包含對 React 編譯器 (React Compiler) 的支援,這是一個旨在通過自動優化元件渲染來提升效能的工具。這減少了手動使用 useMemouseCallback 進行記憶化 (memoization) 的需求。

Next.js 包含一個用 SWC 編寫的自訂效能優化,使 React 編譯器更加高效。Next.js 會分析您的專案,而非在每個檔案上運行編譯器,僅將 React 編譯器應用於相關檔案。這避免了不必要的工作,與單獨使用 Babel 插件相比,能帶來更快的建置速度。

運作原理

React 編譯器通過 Babel 插件運行。為了保持建置速度,Next.js 使用了一個自訂的 SWC 優化,僅將 React 編譯器應用於相關檔案——例如包含 JSX 或 React Hooks 的檔案。

這避免了編譯所有內容,並將效能影響降至最低。與預設的基於 Rust 的編譯器相比,您可能仍會看到建置速度稍慢,但影響很小且局部化。

要使用它,請安裝 babel-plugin-react-compiler

Terminal
npm install babel-plugin-react-compiler

然後,在 next.config.js 中添加 experimental.reactCompiler 選項:

import type { NextConfig } from 'next'

const nextConfig: NextConfig = {
  experimental: {
    reactCompiler: true,
  },
}

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

module.exports = nextConfig

註解 (Annotations)

您可以配置編譯器以「選擇加入」(opt-in) 模式運行,如下所示:

import type { NextConfig } from 'next'

const nextConfig: NextConfig = {
  experimental: {
    reactCompiler: {
      compilationMode: 'annotation',
    },
  },
}

export default nextConfig
/** @type {import('next').NextConfig} */
const nextConfig = {
  experimental: {
    reactCompiler: {
      compilationMode: 'annotation',
    },
  },
}

module.exports = nextConfig

然後,您可以使用 React 的 "use memo" 指令來註解特定元件或 Hook 以選擇加入:

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

注意: 您也可以使用 React 的 "use no memo" 指令來達到相反的效果,即選擇退出 (opt-out) 某個元件或 Hook。