reactCompiler
启用 React Compiler 以自动优化组件渲染。
Next.js 支持 React Compiler,这是一个通过自动优化组件渲染来提升性能的工具。它减少了对 useMemo 和 useCallback 进行手动记忆化(memoization)的需求。
Next.js 内置了一个用 SWC 编写的自定义性能优化,可让 React Compiler 更高效。Next.js 不会在每个文件上运行编译器,而是分析你的项目,仅将 React Compiler 应用于相关文件。这样避免了不必要的工作,与单独使用 Babel 插件相比,构建速度更快。
工作原理
React Compiler 通过 Babel 插件运行。为了保持构建速度,Next.js 使用自定义的 SWC 优化,仅将 React Compiler 应用于相关文件,例如包含 JSX 或 React Hooks 的文件。
这样避免了编译所有内容,并将性能开销降到最低。与默认的基于 Rust 的编译器相比,你可能仍会看到构建速度略慢,但影响很小且仅限于局部。
要使用它,请安装 babel-plugin-react-compiler:
pnpm
pnpm add -D babel-plugin-react-compiler
npm
npm install -D babel-plugin-react-compiler
yarn
yarn add -D babel-plugin-react-compiler
bun
bun add -D babel-plugin-react-compiler
然后,在 next.config.js 中添加 reactCompiler 选项:
TypeScript
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
reactCompiler: true,
}
export default nextConfig
JavaScript
/** @type {import('next').NextConfig} */
const nextConfig = {
reactCompiler: true,
}
module.exports = nextConfig
注解
你可以按如下方式将编译器配置为以 "opt-in"(按需启用)模式运行:
TypeScript
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
reactCompiler: {
compilationMode: 'annotation',
},
}
export default nextConfig
JavaScript
/** @type {import('next').NextConfig} */
const nextConfig = {
reactCompiler: {
compilationMode: 'annotation',
},
}
module.exports = nextConfig
然后,你可以使用 React 的 "use memo" 指令标注特定的组件或 Hook,以选择启用:
TypeScript
export default function Page() {
'use memo'
// ...
}
JavaScript
export default function Page() {
'use memo'
// ...
}
注意:
你也可以使用 React 的
"use no memo"指令实现相反的效果,将某个组件或 Hook 排除在外(opt-out)。
现有的记忆化保证
你可以配置编译器是否保留来自 useMemo、useCallback 和 React.memo 的现有记忆化保证:
TypeScript
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
reactCompiler: {
environment: {
enablePreserveExistingMemoizationGuarantees: false,
},
},
}
export default nextConfig
JavaScript
/** @type {import('next').NextConfig} */
const nextConfig = {
reactCompiler: {
environment: {
enablePreserveExistingMemoizationGuarantees: false,
},
},
}
module.exports = nextConfig
省略时,Next.js 使用当前启用的 React Compiler 实现的默认值。由于不同编译器实现和版本之间的默认值可能不同,请显式设置此选项以确保行为一致。
版本历史
| 版本 | 变更 |
|---|---|
v16.0.0 |
reactCompiler 已稳定,并从 experimental.reactCompiler 移至顶层的 reactCompiler 选项。 |