最近在寫一個(gè)react-ant-admin的集成框架用于快速搭載中后臺(tái)項(xiàng)目。其中遇到很多問題,最重要的應(yīng)該是訪問速度了。我就想 react 可不可以和 vue 一樣用路由懶加載來減少首頁(yè)渲染所花費(fèi)的時(shí)間。
于是找到了一個(gè)很好用的輪子:@loadable/component
使用
安裝
npm install @loadable/component -D # or use yarn yarn add @loadable/component -D
如何在路由中使用?
在src/router/index.js文件中按照如下舉例來寫:
import React from "react"; import { Route, Switch } from "react-router-dom"; import routerList from "./routes"; const router = () => { return ( <Switch> {routerList.map((item) => { const { component: Component, key, path, ...itemProps } = item; return ( <Route exact={true} key={key} path={path} render={(allProps) => <Component {...allProps} {...itemProps} />} /> ); })} </Switch> ); }; export default router;
在src/router/routes.js
文件按照如下舉例來寫:
import loadable from "@loadable/component"; const Error404 = loadable(() => import("@/pages/err/404")); // 對(duì)應(yīng)文件 src/pages/err/404.js const Home = loadable(() => import("@/pages/home")); const Demo = loadable(() => import("@/pages/demo")); const routerList = [ { path: "/", key: "home", components: Home, }, { path: "/demo", key: "demo", components: Demo, }, { path: "*", key: "404", components: Error404, }, ]; export default routerList;
在src/App.js
文件按照如下舉例來寫:
import React from "react"; import { BrowserRouter as Router } from "react-router-dom"; import Routes from "./router"; export default function App() { return ( <Router> <Routes /> </Router> ); }
此時(shí)可以去頁(yè)面查看切換路由的時(shí)候是否動(dòng)態(tài)加載了 js 文件。若切換路由加載了 js 文件,說明懶加載路由成功!
加載速度對(duì)比
在沒有使用@loadable/component
之前
服務(wù)器帶寬1M,gzip壓縮,文件大小2MB左右,服務(wù)器請(qǐng)求加載時(shí)間4.3s左右
使用路由懶加載
服務(wù)器帶寬1M,gzip壓縮,文件大小1MB左右,服務(wù)器請(qǐng)求加載時(shí)間1s左右
以上就是react如何利用懶加載減少首屏加載時(shí)間的詳細(xì)內(nèi)容,更多關(guān)于react懶加載減少加載時(shí)間的資料請(qǐng)關(guān)注服務(wù)器之家其它相關(guān)文章!
原文鏈接:https://www.cnblogs.com/kongyijilafumi/p/14652854.html