Next.js 中的懒加载通过减少渲染路由所需的 JavaScript 量,帮助提高应用程序的初始加载性能。
它允许您推迟加载客户端组件和导入的库,并仅在需要时将其包含在客户端 bundle 中。例如,您可能希望将模态框的加载推迟到用户点击打开它时。
在 Next.js 中实现懒加载有两种方法:
next/dynamic 进行动态导入React.lazy() 配合 Suspense默认情况下,服务器组件会自动进行代码分割,并且您可以使用流式传输逐步将 UI 片段从服务器发送到客户端。懒加载适用于客户端组件。
next/dynamicnext/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>
)
}注意: 当服务器组件动态导入客户端组件时,目前不支持自动代码分割。
当使用 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选项。如果您尝试在服务器组件中使用它,将会看到一个错误。
在服务器组件中,next/dynamic不允许使用ssr: false。请将其移至客户端组件中。
外部库可以使用 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/dynamicnext/dynamic 是 React.lazy() 和 Suspense 的组合。它在 app 和 pages 目录中的行为方式相同,以支持增量迁移。
在下面的示例中,通过使用 next/dynamic,头部组件将不会包含在页面的初始 JavaScript bundle 中。页面将首先渲染 Suspense 的 fallback,然后在 Suspense 边界解析时渲染 Header 组件。
import dynamic from 'next/dynamic'
const DynamicHeader = dynamic(() => import('../components/header'), {
loading: () => <p>Loading...</p>,
})
export default function Home() {
return <DynamicHeader />
}值得注意的是:在
import('path/to/component')中,路径必须显式编写。它不能是模板字符串,也不能是变量。此外,import()必须在dynamic()调用内部,以便 Next.js 能够将 webpack 包/模块 ID 与特定的dynamic()调用匹配,并在渲染之前预加载它们。dynamic()不能在 React 渲染内部使用,因为它需要在模块的顶层进行标记,以便像React.lazy一样进行预加载。
要动态导入命名导出,您可以从 import() 函数返回的 Promise 中返回它:
export function Hello() {
return <p>Hello!</p>
}
// pages/index.js
import dynamic from 'next/dynamic'
const DynamicComponent = dynamic(() =>
import('../components/hello').then((mod) => mod.Hello)
)要在客户端动态加载组件,您可以使用 ssr 选项禁用服务器渲染。如果外部依赖项或组件依赖于 window 等浏览器 API,此功能会很有用。
'use client'
import dynamic from 'next/dynamic'
const DynamicHeader = dynamic(() => import('../components/header'), {
ssr: false,
})此示例使用外部库 fuse.js 进行模糊搜索。该模块仅在用户在搜索输入框中输入后才在浏览器中加载。
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>
)
}