基于路由的拆分
我们可以通过添加基于路由的拆分来请求仅在特定路由下才需要的资源。通过将**React Suspense**或loadable-components
与react-router
等库结合,我们可以根据当前路由动态加载组件。
index.js
1import React, { lazy, Suspense } from "react";2import { render } from "react-dom";3import { Switch, Route, BrowserRouter as Router } from "react-router-dom";45const App = lazy(() => import(/* webpackChunkName: "home" */ "./App"));6const Overview = lazy(() =>7 import(/* webpackChunkName: "overview" */ "./Overview")8);9const Settings = lazy(() =>10 import(/* webpackChunkName: "settings" */ "./Settings")11);1213render(14 <Router>15 <Suspense fallback={<div>Loading...</div>}>16 <Switch>17 <Route exact path="/">18 <App />19 </Route>20 <Route path="/overview">21 <Overview />22 </Route>23 <Route path="/settings">24 <Settings />25 </Route>26 </Switch>27 </Suspense>28 </Router>,29 document.getElementById("root")30);3132module.hot.accept();
通过按路由延迟加载组件,我们只请求包含当前路由所需代码的包。由于大多数人已经习惯了重定向过程中可能会有加载时间,因此这是延迟加载组件的绝佳时机!