可以通过添加基于路由的拆分来请求仅特定路由需要的资源。
通过将 React Suspense
或 loadable-component
与 react-router
等库结合,可以根据当前路由动态加载组件。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
|
import React, { lazy, Suspense } from "react";
import { render } from "react-dom";
import { Switch, Route, BrowserRouter as Router } from "react-router-dom";
const App = lazy(() => import(/* webpackChunkName: "home" */ "./App"));
const Overview = lazy(() =>
import(/* webpackChunkName: "overview" */ "./Overview")
);
const Settings = lazy(() =>
import(/* webpackChunkName: "settings" */ "./Settings")
);
render(
<Router>
<Suspense fallback={<div>Loading...</div>}>
<Switch>
<Route exact path="/">
<App />
</Route>
<Route path="/overview">
<Overview />
</Route>
<Route path="/settings">
<Settings />
</Route>
</Switch>
</Suspense>
</Router>,
document.getElementById("root")
);
module.hot.accept();
|
通过延迟加载每个路由的组件,只请求包含当前路由所需代码的包。
由于大多数人已经习惯了重定向期间可能会有一些加载时间的事实,因此它是延迟加载组件的理想场所!
知识点
-
React Suspense
-
loadable-component
-
react-router