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

本文介绍三种React Router按需加载的方法:使用react-loadable、route3的getComponent及create-react-app推荐方案。第三种方法较为简洁实用,通过创建异步组件并结合Webpack实现动态导入。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

 

第一种:

 

利用react-loadable这个高级组件,要做到实现按需加载这一点,我们将使用WebPack,babel-plugin-syntax-dynamic-importreact-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的加载效果

 

更多文章jacktesla的博客

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值