安裝依賴:
yarn add react-loadable
創建通用工具類:
src/util/loadable.js
/*路由懶加載(異步組件)*/
import React from 'react';
import Loadable from 'react-loadable';
//通用的過場組件
const LoadingComponent =()=>{
return (
<div>loading</div>
)
}
//過場組件默認采用通用的,若傳入了loading,則采用傳入的過場組件
export default (loader,loading = LoadingComponent)=>{
return Loadable({
loader,
loading
});
}
router里面調用方式改為如下
/*配置路由*/
import React, { Fragment } from 'react'
import { BrowserRouter, Route } from 'react-router-dom'
import loadable from '../util/loadable'
const Home = loadable(()=>import('@pages/home'))
const Routes = () => (
<BrowserRouter>
<Route path="/home" component={Home}/>
</BrowserRouter>
);
export default Routes
封裝之后,laodable只需寫一次,改變的只是組件的引入方式,這樣一來就方便多了,
react-loadable是以組件級別來分割代碼的,這意味着,我們不僅可以根據路由按需加載,還可以根據組件按需加載,使用方式和路由分割一樣,只用修改組件的引入方式即可
