【发布时间】:2018-06-21 06:21:41
【问题描述】:
我们开发了一个供内部使用的 React 组件库。该库使用 webpack 将所有内容捆绑到 bundle.js 中。该库作为 NPM 模块公开,供我们的应用程序使用,到目前为止效果很好。
最近我们添加了一个 Grid 组件,它具有一些非常大的外部依赖项。即使我们的一些应用程序不需要库中的这个组件,我们还是决定将它包含在最终的包中。这会对包的大小产生巨大的影响,所以我按照 Webpack 的 code splitting guide 使用动态导入来分解 Grid 组件。对于我们将这个库安装为 NPM 模块的应用程序,组件库包现在在 node_modules 中看起来像这样:
├── node_modules/
│ ├── [our component library]/
│ │ ├── Grid.js # Asynchronously loaded Grid component
│ │ ├── bundle.js # Main bundle
│ │ └── ... other files in component library bundle
在构建应用程序时(也使用 Webpack),Grid 组件似乎没有作为自己的文件包含在最终包中。事实上,它根本没有被包括在内:
├── dist/
│ ├── main.js # App bundle
│ ├── vendor.js # Vendor bundle created with CommonChunksPlugin
│ └── ... other files in application bundle but no Grid.js
当尝试在浏览器中加载使用异步加载的 Grid 组件的页面时,Webpack 返回以下错误:
Error: Loading chunk 0 failed.
at HTMLScriptElement.onScriptComplete (bundle.js:757)
本质上,这表示找不到 Grid 组件块。我究竟做错了什么?甚至可以像这样对 React 组件库进行代码拆分吗?
【问题讨论】:
-
为什么不让内部库中的每个组件都可以单独导入?不需要为此进行代码拆分。 Webpack 只会在最终的包中包含真正导入的内容。
-
@trixn 当您说“可单独导入”时,您的意思是为库中的每个组件创建一个入口点吗?我还能做到
import { Component } from 'component-library'吗? -
你能显示你的入口点文件和 webpack 配置吗?