react

create-react-app 按需加载以及部署

2017-09-27  本文已影响292人  xiaohesong

闲来无事,就想着把前几天折腾的问题重新梳理一遍,加深印象.
上面一篇文章有提到升级ejectcra项目.为什么升级这个项目,就是想要折腾,就是想要使用到webpack2,还有一个好处是加深对create-react-app的理解.坏处不言而喻,折腾浪费生命浪费时间.

按需加载

import React, { Component } from "react";

export default function asyncComponent(importComponent) {
    class AsyncComponent extends Component {
        constructor(props) {
            super(props);

            this.state = {
                component: null
            };
        }

        async componentDidMount() {
            const { default: component } = await importComponent();

            this.setState({
                component: component
            });
        }

        render() {
            const Component = this.state.component;

            return Component ? <Component {...this.props} /> : null;
        }
    }

    return AsyncComponent;
}

这个是异步加载组件的方法.到时在需要的组件上加入引用就好.例如在路由里.

const AsyncUser = asyncComponent(() => import("./User"));
...
<Route path="/users" component={AsyncUser}/>

部署(nginx以及npm2)

参考

上一篇 下一篇

猜你喜欢

热点阅读