我应该使用 react-loadable 还是 loadable-components 进行代码拆分?

Should I use react-loadable or loadable-components for code splitting?

我想将我的 React 代码与服务器端渲染分开。为此,我有两个选择。

可加载组件

React 文档建议对服务器呈现的应用程序使用 loadable-components。但是它的 NPM 每周下载量很少。

可反应加载

这个包的 NPM 每周下载量与前一个相比非常高,但根据 loadable-components 文档,这个包不再维护。

react-loadable was the recommended way for React code splitting for a long time. However, today it is not maintained any more and it is not compatible with Webpack v4+ and Babel v7+. Documentation Link

请帮我提供合适的包裹。

您可以使用 React.lazy。 这将在呈现此组件时自动加载包含 OtherComponent 的包。

React.lazy 采用必须调用动态 import() 的函数。这必须 return 一个 Promise,它解析为一个模块,默认导出包含一个 React 组件。

const OtherComponent = React.lazy(() => import('./OtherComponent'));

function MyComponent() {
  return (
    <div>
      <OtherComponent />
    </div>
  );
}

尽管 react-loadable 的文档说 react-loadable 与 Webpack v4+ 和 Babel v7+ 不兼容,但我使用了 react-loadable 并且成功了。我在服务器端和客户端渲染应用程序中都没有遇到任何问题。

FWIW loadable-componentsReact team

推荐

此外,React.lazy 目前不支持 SSR(截至 2020 年 5 月)