懒加载
Next.js 中懒加载通过减少渲染路由所需的 JavaScript 数量有助于提高应用程序的初始加载性能。
它允许您延迟加载客户端组件 和导入的库,并仅在需要时将它们包含在客户端包中。例如,您可能希望延迟加载模态框,直到用户点击打开它时在加载。
在 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:
const ComponentC = dynamic(() => import("../components/C"), { ssr: false });
导入服务器组件
如果您动态导入一个服务器组件,只有该服务器组件的子客户端组件会被懒加载-服务器组件本身不会被懒加载。
import dynamic from "next/dynamic";
// Server Component:
const ServerComponent = dynamic(() => import("../components/ServerComponent"));
export default function ServerComponentExample() {
return (
<div>
<ServerComponent />
</div>
);
}
加载外部库
外部库可以使用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>
);
}
添加自定义 loading 组件
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)
);