摘要:React 代码分割(Code Splitting)主要是为了优化首屏加载速度,避免一次性加载整个应用,把代码拆分成多个 bundle,按需加载。常见的方式有三种:
React 代码分割(Code Splitting)主要是为了 优化首屏加载速度,避免一次性加载整个应用,把代码拆分成多个 bundle,按需加载。常见的方式有三种:
适合组件级别的代码分割。
import React, { Suspense } from "react";// 按需加载组件const PerformanceReport = React.lazy( => import("./pages/PerformanceReport"));function App {return (云鉴性能平台
Loading...}>);}export default App;React.lazy:实现组件的懒加载Suspense:加载时的兜底 UI(比如 Loading 动画)如果你用 react-Router-dom,可以结合 React.lazy 在路由层做代码分割。
import React, { Suspense } from "react";import { BrowserRouter as Router, Routes, Route } from "react-router-dom";const PerformanceQuery = React.lazy( => import("./pages/PerformanceQuery"));const PerformanceReport = React.lazy( => import("./pages/PerformanceReport"));function AppRouter {return (页面加载中...}>} />} />);}export default AppRouter;常见做法:
首页加载最少的 bundle进入对应页面时再动态加载该页面的 JS适合某些 工具类模块 或 特定场景的函数,避免一开始全量加载。
async function loadExcelExport {const { exportToExcel } = await import("./utils/excelExport");exportToExcel;}建议实践:
来源:盛阳教育