1. 程式人生 > >React loadable 按需載入 個人使用記錄

React loadable 按需載入 個人使用記錄

包需要 install

babel-plugin-syntax-dynamic-import

webpack.config的babelrc需要在plugins裡新增

"syntax-dynamic-import"

快捷使用,封裝成元件

import React from 'react';
import Loadable from 'react-loadable';

import {Row, Col,Card} from 'antd';
// 按需載入元件
export default function withLoadable (comp) {
    return Loadable({
        loader:comp,
        loading:(props)=>{
            if (props.error) {
                return <Card style={{width:"100%",height:"100%"}} >
                    載入錯誤。請重新整理
                </Card>;
            } else if (props.timedOut) {
                return <Card style={{width:"100%",height:"100%"}} >
                    載入超時。請重新整理
                </Card>;
            } else if (props.pastDelay) {
                return <Card loading={true} style={{width:"100%",height:"100%"}} />;
            } else {
                return null;
            }
        },
        timeout:10000
    })
}

元件使用方法,可以將原先匯入的元件變為按需載入的元件

import React from 'react';
import {connect} from 'react-redux';
// import Main from './main'
// import Info from './info'
// import Add from './add'
import {HashRouter, BrowserRouter, Route, NavLink, Switch, Redirect, withRouter} from 'react-router-dom';

import Loadable from '../../../commom/loadable';

const Main = Loadable(() => import('./main'));
const Info = Loadable(() => import('./info'));
const Add = Loadable(() => import('./add'));

export default () => {
    return (
        <Switch>
            <Route path="/high/manager/" exact component={Main}/>
            <Route path="/high/manager/info" exact component={Info}/>
            <Route path="/high/manager/add" exact component={Add}/>
        </Switch>
    );
}

拆分的js檔案,這拆分效率也太高了8!!!還不用修改任何配置!

之前遇到的問題:

一開始在頂層路由使用,發現某些路由使用元件並編譯後並沒有生成拆分的程式碼包,因為不瞭解原理,後來根據loadable高價元件的基於元件的按需載入思想,將按需載入元件置於相對更底層的元件中,發現成功生成對應拆分的程式碼包。