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