Next.js 包含对 React 编译器的支持,这是一款旨在通过自动优化组件渲染来提高性能的工具。这减少了手动使用 useMemo 和 useCallback 进行记忆化的需求。
Next.js 包含一个用 SWC 编写的自定义性能优化,它使 React 编译器更加高效。Next.js 不会在每个文件上运行编译器,而是分析你的项目,只将 React 编译器应用于相关文件。这避免了不必要的工作,与单独使用 Babel 插件相比,可以实现更快的构建。
React 编译器通过 Babel 插件运行。为了保持构建速度,Next.js 使用了自定义的 SWC 优化,它只将 React 编译器应用于相关文件——例如包含 JSX 或 React Hooks 的文件。
这避免了编译所有内容,并将性能开销降到最低。与默认的基于 Rust 的编译器相比,你可能会看到构建速度略有下降,但影响很小且局限于局部。
要使用它,请安装 babel-plugin-react-compiler:
npm install -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你可以按如下方式将编译器配置为在“选择加入”模式下运行:
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。