主题
reactCompiler
Next.js 包含对 React 编译器 的支持,React 编译器 是一个旨在通过自动优化组件渲染来提高性能的工具。这减少了使用 useMemo
和 useCallback
进行手动记忆的需要。
¥Next.js includes support for the React Compiler, a tool designed to improve performance by automatically optimizing component rendering. This reduces the need for manual memoization using useMemo
and useCallback
.
Next.js 包含一个用 SWC 编写的自定义性能优化器,可以提高 React 编译器的效率。Next.js 不会在每个文件上运行编译器,而是会分析你的项目,并仅将 React 编译器应用于相关文件。与单独使用 Babel 插件相比,这避免了不必要的工作,并提高了构建速度。
¥Next.js includes a custom performance optimization written in SWC that makes the React Compiler more efficient. Instead of running the compiler on every file, Next.js analyzes your project and only applies the React Compiler to relevant files. This avoids unnecessary work and leads to faster builds compared to using the Babel plugin on its own.
工作原理
¥How It Works
React 编译器通过 Babel 插件运行。为了保持快速构建,Next.js 使用自定义 SWC 优化,该优化仅将 React 编译器应用于相关文件(例如带有 JSX 或 React Hooks 的文件)。
¥The React Compiler runs through a Babel plugin. To keep builds fast, Next.js uses a custom SWC optimization that only applies the React Compiler to relevant files—like those with JSX or React Hooks.
这避免了编译所有内容,并将性能成本降至最低。与默认的基于 Rust 的编译器相比,你可能仍然会发现构建速度略慢,但影响很小且只是局部的。
¥This avoids compiling everything and keeps the performance cost minimal. You may still see slightly slower builds compared to the default Rust-based compiler, but the impact is small and localized.
要使用它,请安装 babel-plugin-react-compiler
:
¥To use it, install the babel-plugin-react-compiler
:
bash
npm install babel-plugin-react-compiler
然后,在 next.config.js
中添加 experimental.reactCompiler
选项:
¥Then, add experimental.reactCompiler
option in next.config.js
:
ts
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
experimental: {
reactCompiler: true,
},
}
export default nextConfig
js
/** @type {import('next').NextConfig} */
const nextConfig = {
experimental: {
reactCompiler: true,
},
}
module.exports = nextConfig
注释
¥Annotations
你可以将编译器配置为在 "opt-in" 模式下运行,如下所示:
¥You can configure the compiler to run in "opt-in" mode as follows:
ts
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
experimental: {
reactCompiler: {
compilationMode: 'annotation',
},
},
}
export default nextConfig
js
/** @type {import('next').NextConfig} */
const nextConfig = {
experimental: {
reactCompiler: {
compilationMode: 'annotation',
},
},
}
module.exports = nextConfig
然后,你可以使用 React 中的 "use memo"
指令注释特定组件或钩子以选择加入:
¥Then, you can annotate specific components or hooks with the "use memo"
directive from React to opt-in:
ts
export default function Page() {
'use memo'
// ...
}
js
export default function Page() {
'use memo'
// ...
}
注意:你还可以使用 React 中的
"use no memo"
指令来获得相反的效果,以选择退出组件或钩子。¥Note: You can also use the
"use no memo"
directive from React for the opposite effect, to opt-out a component or hook.