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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM