react代碼分割的三種實現(xiàn)方法
React 代碼分割(Code Splitting)主要是為了 優(yōu)化首屏加載速度,避免一次性加載整個應(yīng)用,把代碼拆分成多個 bundle,按需加載。常見的方式有三種:
1. 使用React.lazy+Suspense(推薦方式)
適合組件級別的代碼分割。
import React, { Suspense } from "react"; // 按需加載組件 const PerformanceReport = React.lazy(() => import("./pages/PerformanceReport")); function App() { return ( <div> <h1>云鑒性能平臺</h1> <Suspense fallback={<div>Loading...</div>}> <PerformanceReport /> </Suspense> </div> ); } export default App;
React.lazy
:實現(xiàn)組件的懶加載Suspense
:加載時的兜底 UI(比如 Loading 動畫)
2. 路由級別代碼分割(React Router)
如果你用 react-router-dom
,可以結(jié)合 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 ( <Router> <Suspense fallback={<div>頁面加載中...</div>}> <Routes> <Route path="/query" element={<PerformanceQuery />} /> <Route path="/report" element={<PerformanceReport />} /> </Routes> </Suspense> </Router> ); } export default AppRouter;
?? 常見做法:
- 首頁加載最少的 bundle
- 進入對應(yīng)頁面時再動態(tài)加載該頁面的 JS
3.動態(tài) import(webpack 原生支持)
適合某些 工具類模塊 或 特定場景的函數(shù),避免一開始全量加載。
async function loadExcelExport() { const { exportToExcel } = await import("./utils/excelExport"); exportToExcel(); }
4. 更高級的代碼分割工具
- Loadable Components:更靈活的懶加載方案,支持 SSR。
- Webpack SplitChunksPlugin:拆分公共代碼,比如
react
,lodash
。 - Vite/Rollup:天然支持動態(tài) import,自動分割 bundle。
?? 建議實踐:
- 路由層做大塊分割(每個頁面一個 bundle)
- 工具函數(shù)/圖表庫按需 import(避免首頁加載太大)
- 配合 瀏覽器緩存,重復(fù)訪問時會更快
到此這篇關(guān)于react代碼分割的三種實現(xiàn)方法的文章就介紹到這了,更多相關(guān)react代碼分割內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
深入理解React調(diào)度(Scheduler)原理
本文主要介紹了深入理解React調(diào)度(Scheduler)原理,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-07-07一篇文章介紹redux、react-redux、redux-saga總結(jié)
這篇文章主要介紹了一篇文章介紹redux、react-redux、redux-saga總結(jié),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2019-05-05