Nextjs的懒加载使用方法

在项目中,适当地对一些比较重的模块进行懒加载处理,能提高应用的初始化加载速度, nextjs提供了nextjs/dynamic这个模块来实现懒加载。

基础例子

jsx 复制代码
'use client'

import { useCallback, useState } from 'react'
import dynamic from 'next/dynamic'
const ComponentA = dynamic(() => import('./components/A'))
const ComponentB = dynamic(() => import('./components/B'))
const ComponentC = dynamic(() => import('./components/C'), { ssr: false })

const WithCustomLoading = dynamic(
  () => import('./components/B'),
  {
    loading: () => <p>Loading...</p>,
  }
)

export default function Home() {
  const [visible, setVisible] = useState(false)
  const handleTrigger = useCallback(() => { setVisible(!visible) })
  return (
    <main>

      {/* 模块 A 会被分包,并且立即加载 */}
      <ComponentA />
      {/* 模块 B 会按需加载 */}
      {visible && <ComponentB />}
      {/* 模块 C 会被分包,并且关闭ssr 模式,在客户端执行 */}
      <ComponentC />

      <button onClick={handleTrigger}>trigger</button>
    </main>
  )
}

加载情况可以看下面的截图,模块 A 和模块 C 都被分包

当点击了按钮,将visible的值改为 true 时,模块 B 也被动态加载。

懒加载外部库

可以用到import()来引入模块

module.a.js

js 复制代码
export const name = 1
export const isModule = true
js 复制代码
// 通过相对路径来引入模块
import("./module.a").then(({ name, isModule }) => {
  console.log(name, isModule)
})
// 引入外部库
import("fuse.js").then((module) => {
  const Fuse = module.default
  console.log(Fuse)
})

懒加载组件时的加载回显

js 复制代码
import dynamic from 'next/dynamic'

const WithCustomLoading = dynamic(
  () => import('../components/WithCustomLoading'),
  {
    loading: () => <p>Loading...</p>,
  }
)

export default function Page() {
  return (
    <div>
      {/* 当组件加载时会展示 loading 状态  <WithCustomLoading/> */}
      <WithCustomLoading />
    </div>
  )
}

效果如下

相关推荐
wangruofeng16 分钟前
AI Models 1.1.0 发布,查大模型价格、对比模型和找 API 地址
前端·aigc·ai编程
wangruofeng19 分钟前
给前端开发者的 100 个设计参考网站
前端·设计
星栈3 小时前
视频即代码,Remotion 能做什么、不能做什么
前端·音视频开发
广州华水科技3 小时前
单北斗GNSS位移监测系统的应用与技术解析
前端
用户47949283569154 小时前
从一句话或代码仓到可交互 HTML:开源 Agent 画图技能 Archify v3.2 实测与选型边界
前端·后端·面试
风骏时光牛马6 小时前
生成一个AI多模态标题,仅输出一条标题,无额外文字、问句、备选、配图、文案等任何附加内容,不需要其他的任务服务 只要标题。
前端
wangruofeng7 小时前
从 GIF 到 AVIF:网页图片格式演进与 2026 年选型指南
前端·架构
清晨Coding8 小时前
为什么用 React Developer Tools 查看组件树这么乱?
前端·react.js
鶴哥只手遮天8 小时前
《Electron 45.2.3 内核解剖》第 4 章 补丁体系:380 个补丁改了什么
前端·electron
FungLeo10 小时前
成为全栈·Vue 管理后台篇·分类树与标签管理:层级数据如何落到管理界面
前端·javascript·vue.js·分类树·naive ui·标签管理·前端数据结构