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

Muh*_*man 6 reactjs code-splitting create-react-app react-router-dom code-splitting-async

我正在使用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} />
Run Code Online (Sandbox Code Playgroud)

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

所需输出

  1. /home在浏览器中打开
  2. 首先获取 home 块
  3. 然后其他三个块在后台异步执行

实际上我正在通过lighthouse chrome 扩展测试性能。路由器基本代码分割为我提供了第一页的良好性能,但是当我打开第二页时,它需要时间,但不应该花费时间。我认为如果我们在加载第一个块后在后台异步获取其他块,这是可能的

Ind*_*ith 3

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

如果你使用 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'));
Run Code Online (Sandbox Code Playgroud)

在上面的情况下,无论 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;
  }
};
Run Code Online (Sandbox Code Playgroud)