react-router 4實現代碼分割(code spliting)

官方一開始推薦的使用bundle-loader來作代碼分割的方式感受有點麻煩,並且代碼看起來有點不舒服。並且須要一直依賴bunder-loadervue

一開始我想爲何不能像vue同樣,直接使用ES的新特性import()來實現呢,後來在網上一查,果真有大神實現了這個方案。react

這個方案看起來很是簡潔,只須要封裝一個HOC便可,大致的代碼以下git

import React from 'react';
export default function asyncComponent(importComponent) {
    class AsyncComponent extends React.Component {
        constructor(props) {
            super(props);
            this.state = {component: null};
        }
        async componentDidMount() {
            const {default: component} = await importComponent();
            this.setState({component});
        }
        render() {
            const Comp = this.state.component
            return Comp ? <Comp {...this.props} /> : null;
        }
    }
    return AsyncComponent;
}

之後在引入組件是隻須要一個簡單的調用便可github

const AsyncAbout = asyncComponent(() => import('./views/about.js'));

順便吐槽下,react-router4真的要比react-router3難用多了,真的噁心。懷戀當時直接使用require.ensure()就能夠實現code spliting的時候react-router

我我的的react練手項目在 https://github.com/lznism/xiachufang-react,項目比較簡潔,歡迎star交流~async

相關文章
相關標籤/搜索