如何懒加载客户端组件和库
懒加载导入的库和 React 组件,以提升应用的加载性能。
Next.js 中的懒加载通过减少渲染路由所需的 JavaScript 数量,帮助提升应用的初始加载性能。
它允许你延迟加载客户端组件和导入的库,只在需要时才将它们包含在客户端 bundle 中。例如,你可能希望延迟加载模态框,直到用户点击打开它。
在 Next.js 中,有两种方式可以实现懒加载:
- 使用 动态导入 配合
next/dynamic - 使用
React.lazy()配合 Suspense
默认情况下,服务器组件会自动进行代码分割,你可以使用流式渲染逐步将 UI 片段从服务器发送到客户端。懒加载适用于客户端组件。
next/dynamic
next/dynamic 是 React.lazy() 和 Suspense 的组合。它在 app 和 pages 目录中的行为相同,以便支持渐进式迁移。
示例
导入客户端组件
'use client'
import { useState } from 'react'
import dynamic from 'next/dynamic'
// Client Components:
const ComponentA = dynamic(() => import('../components/A'))
const ComponentB = dynamic(() => import('../components/B'))
const ComponentC = dynamic(() => import('../components/C'), { ssr: false })
export default function ClientComponentExample() {
const [showMore, setShowMore] = useState(false)
return (
<div>
{/* Load immediately, but in a separate client bundle */}
<ComponentA />
{/* Load on demand, only when/if the condition is met */}
{showMore && <ComponentB />}
<button onClick={() => setShowMore(!showMore)}>Toggle</button>
{/* Load only on the client side */}
<ComponentC />
</div>
)
}
注意:
当服务器组件动态导入客户端组件时,目前不支持自动代码分割。
跳过 SSR
使用 React.lazy() 和 Suspense 时,客户端组件默认会被预渲染(SSR)。
注意:
ssr: false选项仅对客户端组件有效,请将其移入客户端组件,以确保客户端代码分割正常工作。
如果你想为客户端组件禁用预渲染,可以将 ssr 选项设置为 false:
const ComponentC = dynamic(() => import('../components/C'), { ssr: false })
导入服务器组件
如果你动态导入服务器组件,只有作为该服务器组件子级的客户端组件会被懒加载,服务器组件本身不会。 在服务器组件中使用它时,还有助于预加载 CSS 等静态资源。
import dynamic from 'next/dynamic'
// Server Component:
const ServerComponent = dynamic(() => import('../components/ServerComponent'))
export default function ServerComponentExample() {
return (
<div>
<ServerComponent />
</div>
)
}
注意:
服务器组件不支持
ssr: false选项。如果在服务器组件中尝试使用它,你会看到错误。 在服务器组件中,ssr: false不能与next/dynamic一起使用。请将其移入客户端组件。
加载外部库
可以使用 import() 函数按需加载外部库。此示例使用外部库 fuse.js 进行模糊搜索。该模块仅在用户在搜索输入框中输入后才会在客户端加载。
'use client'
import { useState } from 'react'
const names = ['Tim', 'Joe', 'Bel', 'Lee']
export default function Page() {
const [results, setResults] = useState()
return (
<div>
<input
type="text"
placeholder="Search"
onChange={async (e) => {
const { value } = e.currentTarget
// Dynamically load fuse.js
const Fuse = (await import('fuse.js')).default
const fuse = new Fuse(names)
setResults(fuse.search(value))
}}
/>
<pre>Results: {JSON.stringify(results, null, 2)}</pre>
</div>
)
}
添加自定义加载组件
'use client'
import dynamic from 'next/dynamic'
const WithCustomLoading = dynamic(
() => import('../components/WithCustomLoading'),
{
loading: () => <p>Loading...</p>,
}
)
export default function Page() {
return (
<div>
{/* The loading component will be rendered while <WithCustomLoading/> is loading */}
<WithCustomLoading />
</div>
)
}
导入命名导出
要动态导入命名导出,可以从 import() 函数返回的 Promise 中返回它:
'use client'
export function Hello() {
return <p>Hello!</p>
}
import dynamic from 'next/dynamic'
const ClientComponent = dynamic(() =>
import('../components/hello').then((mod) => mod.Hello)
)
魔术注释
Next.js 支持魔术注释,用于控制打包器如何处理动态导入。这些注释适用于动态 import()、require()、require.resolve() 和 new Worker() 表达式。
须知:
魔术注释不适用于静态
import语句(import x from 'y')。它们仅适用于动态表达式。
webpackIgnore / turbopackIgnore
使用这些注释可以跳过对动态导入的打包。导入表达式将在输出中保持原样,这适用于仅在运行时使用的模块:
// Skip bundling - import happens at runtime
const runtime = await import(/* webpackIgnore: true */ 'runtime-module')
// Turbopack-specific variant
const plugin = await import(/* turbopackIgnore: true */ pluginPath)
// Also works with require
const mod = require(/* webpackIgnore: true */ 'runtime-module')
turbopackOptional(仅限 Turbopack)
当模块可能不存在时,使用此注释可以抑制构建错误。如果模块缺失,导入仍会在运行时抛出错误:
// No build error if './optional-feature' doesn't exist
// Runtime will throw MODULE_NOT_FOUND if executed
const feature = await import(/* turbopackOptional: true */ './optional-feature')
// Also works with require
const mod = require(/* turbopackOptional: true */ './optional-module')
这适用于以下情况:
- 可能未安装的条件功能
- 模块可选的插件系统
- 某些文件可能尚不存在的渐进式迁移
须知:
不支持
webpackOptional。使用 Turbopack 时请改用turbopackOptional。