【问题标题】:Error when trying to load lazily loaded component from external bundle尝试从外部包加载延迟加载的组件时出错
【发布时间】:2019-07-28 13:23:27
【问题描述】:

我想混合使用 webpack 外部和 React 的延迟加载来优化我的构建。

我的设置摘要如下所示:

shared-ui-components -> 是一个带有 React 组件的 npm 模块,它的构建输出到 s3 存储桶以便主应用程序可以使用。

这是通过 webpack 中的输出配置实现的

  output: {
    //...
    library: 'SUIC',
  }

主应用 -> 使用 shared-ui-components

这是通过 webpack 中的输出配置实现的

  externals: {
    "shared-ui-components": "SUIC"
  }

并将脚本标签链接到存储桶 uri 以包含 shared-ui-components 构建的输出。

这一切都很好。

接下来,由于shared-ui-components中有多个大组件, 我想懒加载一些组件并使用块。

一个例子 sn-p:

import * as React from 'react';
import { lazy, Suspense } from 'react';

const Feed = lazy(() => import('../Feed/Feed'));

const LoadableFeed = () => {
  return <div className="central-comp">
    <Suspense fallback={<p>Loading feed…</p>}>
      <Feed />
    </Suspense>
  </div>
}

export default LoadableFeed

我在两个项目中都使用了tsconfig

 "compilerOptions": {
    "lib": ["es6", "dom"],
    "module": "esnext",
    "moduleResolution": "node",
    "target": "es5",
    "jsx": "react",
    "experimentalDecorators": true,
    "allowSyntheticDefaultImports": true
  }

shared-ui-components 构建似乎正在生成适当的块。

现在,当我在主应用程序中使用 Feed 时,

import { LoadableFeed } from 'shared-ui-components';

const CentralContent = () => {
  return <div className="central-comp">
    <h4>Central Content</h4>
    <LoadableFeed />
  </div>
}

export default CentralContent

我可以看到 shared-ui-components 的 bundle js 可以加载所需的块,但它不能渲染组件。

错误消息说 Uncaught TypeError: Cannot read property 'call' of undefined at o

还有react-dom.development.js:17252 The above error occurred in one of your React components: in Unknown (created by c),我发现c指的是LoadableFeed

似乎主应用程序的包无法呈现shared-ui-components 中定义的延迟加载的组件包,或者延迟加载的组件本身在其他地方使用时无法呈现。

有没有办法解决这个问题?

【问题讨论】:

    标签: reactjs typescript webpack


    【解决方案1】:

    通过在主应用程序的 tsconfig 中将 module 设置为 commonjs 来解决此问题。 有意义的是,最终的应用程序构建输出应该使用 commonjs 而不是 esnext

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-17
      • 1970-01-01
      相关资源
      最近更新 更多