react-router的3种按需加载介绍

react-router的3种按需加载介绍:https://blog.csdn.net/jackTesla/article/details/80792110

react-router的按需加载(推荐第三种)

第一种:
 

利用react-loadable这个高级组件,要做到实现按需加载这一点,我们将使用的WebPack,babel-plugin-syntax-dynamic-import和react-loadable。

webpack内置了对动态导入的支持; 但是,如果使用Babel(将JSX编译为JavaScript),那么将需要使用babel-plugin-syntax-dynamic-import插件。这是一个仅用于语法的插件,这意味着Babel不会做任何额外的转换。该插件只是允许Babel解析动态导入,因此webpack可以将它们捆绑为代码分割。

    .babelrc:

        {

           “ presets ”:[

                       “ react ” 

          ],“ plugins ”:[

                       “ syntax-dynamic-import ” 

          ] 

        }

react-loadable是用于通过动态导入加载组件的高阶组件。

        import Loadable from 'react-loadable';

        import Loading from './Loading';

        const LoadableComponent = Loadable({

                          loader: () => import('./Dashboard'),

                          loading: Loading,

        })

        export default class LoadableDashboard extends React.Component {

            render() {

                        return <LoadableComponent />;

            }

        }

https://github.com/ReactTraining/react-router/blob/master/packages/react-router-dom/docs/guides/code-splitting.md

第二种:
    在router3中的按需加载方式

    route3中实现按需加载只需要按照下面代码的方式实现就可以了。

    const about = (location, cb) => {

        require.ensure([], require => {

            cb(null, require('../Component/about').default)

        },'about')

    }

    //配置route

    <Route path="helpCenter" getComponent={about} />

在router4以前,我们是使用getComponent的的方式来实现按需加载,getComponent是异步的,只有在路由匹配时才会调用,router4中,getComponent方法已经被移除,所以这种方法在router4中不能使用。

第三种:

        create-react-app文档给的react-router按需加载实现:

      本人在自己利用webpack+dva+antd+…的多页应用项目中使用的这个方法,相对简单好用。但是有人指出性能上不如Bundle组件(在react-router 4官网上的一个代码拆分的例子),那个人好像还是Create-react-app的主要贡献者。

第一步:创建一个异步组件

        创建文件src/components/AsyncComponent.js

        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 C = this.state.component;

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

            }

          }

          return AsyncComponent;

        }

第二步:使用异步组件:我们将使用asyncComponent动态导入我们想要的组件。

        const AsyncHome = asyncComponent(() => import("./containers/Home"));

        src/Routes.js:

        import React from "react";

        import { Route, Switch } from "react-router-dom";

        import asyncComponent from "./components/AsyncComponent";

        import AppliedRoute from "./components/AppliedRoute";

        import AuthenticatedRoute from "./components/AuthenticatedRoute";

        import UnauthenticatedRoute from "./components/UnauthenticatedRoute";

        const AsyncHome = asyncComponent(() => import("./containers/Home"));

        const AsyncLogin = asyncComponent(() => import("./containers/Login"));

        const AsyncNotes = asyncComponent(() => import("./containers/Notes"));

        const AsyncSignup = asyncComponent(() => import("./containers/Signup"));

        const AsyncNewNote = asyncComponent(() => import("./containers/NewNote"));

        const AsyncNotFound = asyncComponent(() => import("./containers/NotFound"));

        export default ({ childProps }) =>

          <Switch>

            <AppliedRoute

              path="/"

              exact

              component={AsyncHome}

              props={childProps}

            />

            <UnauthenticatedRoute

              path="/login"

              exact

              component={AsyncLogin}

              props={childProps}

            />

            <UnauthenticatedRoute

              path="/signup"

              exact

              component={AsyncSignup}

              props={childProps}

            />

            <AuthenticatedRoute

              path="/notes/new"

              exact

              component={AsyncNewNote}

              props={childProps}

            />

            <AuthenticatedRoute

              path="/notes/:id"

              exact

              component={AsyncNotes}

              props={childProps}

            />

            {/* Finally, catch all unmatched routes */}

            <Route component={AsyncNotFound} />

          </Switch>

        ;

        这样就可以了,已经做好代码分片的处理了,你可以npm run build 在build目录下看到一些.chunk.js的文件,就是咱们import()的不同动态调用。

        最后在开发者工具中打开network验证.chunk.js的加载效果
————————————————
版权声明:本文为CSDN博主「jackTesla」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/jackTesla/article/details/80792110

猜你喜欢

转载自www.cnblogs.com/bydzhangxiaowei/p/12238776.html