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

相关文章
相关标签/搜索