反应路由器基本代码拆分(获取第一个块,然后在后台异步获取其他块)

我正在使用create-react-app。我想对路由器的基本代码进行拆分,但我想获取用户在浏览器中打开的第一个块,然后在后台异步获取其他块

路线

const HomeModule  = React.lazy(() => import('./modules/ft_home_module/src/main'));
const AuthModule  = React.lazy(() => import('./modules/ft_auth_module/src/main'));
const ProfileModule  = React.lazy(() => import('./modules/ft_profile_module/src/main'));
const MerchantModule  = React.lazy(() => import('./modules/ft_merchant_module/src/main'));

<Route path="/home" component={HomeModule} />
<Route path="/auth" component={AuthModule} />
<Route path="/profile" component={ProfileModule} />
<Route path="/merchant" component={MerchantModule} />

假设,如果用户在浏览器中打开/ home,则将在加载第一个块后首先加载home块,然后在后台异步调用其他块

必需的输出

  1. 在浏览器中打开/home
  2. 先回家获得大块
  3. 然后其他三个块在后台异步

实际上,我正在通过lighthouse chrome extension测试性能。路由器基本代码拆分为我提供了第一页的良好性能,但是当我打开第二页时需要花费一些时间,但不应花费时间。我认为有可能在加载第一个块后在后台使其他块异步

lz407854504 回答:反应路由器基本代码拆分(获取第一个块,然后在后台异步获取其他块)

您可以通过使用浏览器资源提示(预加载和预取)来实现此目的

如果您使用的是webpack,那么魔术注释将很有帮助。您可以尝试这样的事情:

const HomeModule  = React.lazy(() => import(/* webpackPreload: true * /'./modules/ft_home_module/src/main'));
const AuthModule  = React.lazy(() => import(/* webpackPrefetch: true * /'./modules/ft_auth_module/src/main'));
const ProfileModule  = React.lazy(() => import(/* webpackPrefetch: true * /'./modules/ft_profile_module/src/main'));
const MerchantModule  = React.lazy(() => import(/* webpackPrefetch: true */ './modules/ft_merchant_module/src/main'));

在上述情况下,无论使用什么url,它都会预加载homemodule并以低优先级预取其他三个模块。

如果您想要动态行为,可以尝试使用插件: https://github.com/SebastianS90/webpack-prefetch-chunk

添加插件后,您可以使用 webpack_require .pfc方法在后台加载块。

const prefetchChunk = chunkName => {
  if (!window.requestIdleCallback) {
    return;
  } else if (chunkName) {
    let chunkArray = [].concat(chunkName);
    window.requestIdleCallback(() => {
      chunkArray.forEach(chunk => {
        __webpack_require__.pfc(chunk);
      });
    });
  } else {
    return;
  }
};
,

挂起包装路由器,该挂起具有后备功能(如果尚未加载,则在加载块时显示一些内容)...

 import React,{Suspense} from 'react';
 import {Router} from '@reach/router';    

        const HomeModule  = React.lazy(() => import('./modules/ft_home_module/src/main'));
        const AuthModule  = React.lazy(() => import('./modules/ft_auth_module/src/main')) const ProfileModule  = React.lazy(() => import('./modules/ft_profile_module/src/main'));
        const MerchantModule  = React.lazy(() => import('./modules/ft_merchant_module/src/main'));
        const Loading = () => <div>Loading chunk..</div>

            <Suspense fallback={<Loading/>}>
                <Router>
                  <HomeModule path="/home" />
                  <AuthModule path="/auth" />
                  <ProfileModule path="/profile" />
                  <MerchantModule path="/merchant" />
                </Router>
            </Suspense>
本文链接:https://www.f2er.com/2304597.html

大家都在问