react-router 4实现代码分割(code spliting)

官方一开始推荐的使用bundle-loader来做代码分割的方式感觉有点麻烦,而且代码看起来有点不舒服。而且需要一直依赖bunder-loader

一开始我想为什么不能像vue一样,直接使用ES的新特性import()来实现呢,后来在网上一查,果然有大神实现了这个方案。

这个方案看起来非常简洁,只需要封装一个HOC即可,大体的代码如下

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;
}

以后在引入组件是只需要一个简单的调用即可

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

顺便吐槽下,react-router4真的要比react-router3难用多了,真的恶心。怀恋当时直接使用require.ensure()就可以实现code spliting的时候

我个人的react练手项目在 https://github.com/lznism/xiachufang-react,项目比较简洁,欢迎star交流~

posted @ 2018-04-20 22:21  郭励之  阅读(398)  评论(0编辑  收藏  举报