性能优化-react路由懒加载和组件懒加载

背景

随着项目越来越大,打包后的包体积也越来越大,严重影响了首屏加载速度,需要对路由和组件做懒加载处理

主要用到了react中的lazy和Suspense。

废话不多说,直接上干货

路由懒加载

核心代码

js 复制代码
import React, { lazy, Suspense } from "react";
const loading = () => <h3>loading....</h3>;
const Caidan1 = lazy(() => import("@/pages/mud1/caidan1"));

const meunRoutes = [
  {
    name: "模块1",
    path: "/m1",
    icon: <AppstoreOutlined />,
    children: [
      {
        name: "gltf模型",
        path: "/m1/caidan12",
        icon: <AppstoreOutlined />,
        element: (
          <Suspense fallback={loading()}>
            <Caidan1 />
          </Suspense>
        ),
      },
    // 。。。。

配合路由表的完整例子

js 复制代码
// 路由表
import React, { lazy, Suspense } from "react";
import Home from "../pages/home";
import Layout from "@/components/Layout";

const loading = () => <h3>loading....</h3>;

const Caidan1 = lazy(() => import("@/pages/mud1/caidan1"));
const Caidan2 = lazy(() => import("@/pages/mud1/caidan2"));
// 404页面
const NotFound = () => <h1>**** 404 ****</h1>;

const meunRoutes = [
  {
    name: "模块1",
    path: "/m1",
    icon: <AppstoreOutlined />,
    children: [
      {
        name: "gltf模型",
        path: "/m1/caidan12",
        icon: <AppstoreOutlined />,
        element: (
          <Suspense fallback={loading()}>
            <Caidan1 />
          </Suspense>
        ),
      },
      {
        name: "模型动画",
        path: "/m1/caidan13",
        icon: <AppstoreOutlined />,
        element: (
          <Suspense fallback={loading()}>
            <Caidan2 />
          </Suspense>
        ),
      },
    ],
  },
];

// 配置路由表
const routes = [
  {
    path: "/",
    element: <Navigate to="/home" />,
  },
  {
    path: "/home",
    element: <Home />,
  },
  {
    path: "/",
    element: <Layout />,
    children: handleMenuRoutes(meunRoutes),
  },
  { path: "*", element: <NotFound /> },
];

// 处理menu routes
function handleMenuRoutes(arr) {
  let res = [];
  arr.forEach((item) => {
    if (item.children && item.children.length > 0) {
      item.children.forEach((yitem) => {
        let obj = {
          path: yitem.path,
          element: yitem.element,
        };
        res.push(obj);
      });
    }
  });
  return res;
}

const AppRouter = () => useRoutes([...routes]);
export { AppRouter, meunRoutes };

组件懒加载

js 复制代码
import { useEffect, useState, lazy, Suspense } from "react";

const TestCpn = lazy(() => import("@/components/testCpn"));
const Home = () => {
  const [show, setShow] = useState(false);

  function fn() { setShow(true)}

  return (
    <div>
      <button onClick={fn}>加载大组件</button>
      {show && (
        <Suspense>
          <TestCpn />
        </Suspense>
      )}
    </div>
  );
};
export default Home;

效果

组件加载前

组件懒加载后

这样就会大大加快首屏加载速度

相关推荐
我码玄黄18 分钟前
THREE.js:网页上的3D世界构建者
开发语言·javascript·3d
罔闻_spider19 分钟前
爬虫----webpack
前端·爬虫·webpack
吱吱鼠叔21 分钟前
MATLAB数据文件读写:1.格式化读写文件
前端·数据库·matlab
爱喝水的小鼠38 分钟前
Vue3(一) Vite创建Vue3工程,选项式API与组合式API;setup的使用;Vue中的响应式ref,reactive
前端·javascript·vue.js
小晗同学39 分钟前
Vue 实现高级穿梭框 Transfer 封装
javascript·vue.js·elementui
WeiShuai1 小时前
vue-cli3使用DllPlugin优化webpack打包性能
前端·javascript
forwardMyLife1 小时前
element-plus的面包屑组件el-breadcrumb
javascript·vue.js·ecmascript
ice___Cpu1 小时前
Linux 基本使用和 web 程序部署 ( 8000 字 Linux 入门 )
linux·运维·前端
JYbill1 小时前
nestjs使用ESM模块化
前端
加油吧x青年1 小时前
Web端开启直播技术方案分享
前端·webrtc·直播