当我在我的 Web 应用程序中包含一些外部库并开始使用 Webpack (5.45.1) 构建它时,出现了旧错误:Cannot read property <..> of undefined
。进入杂草,我发现问题是循环依赖。外部库请求 Node.js util
一个,随后的依赖关系图看起来像这样:
./node_modules/util/util.js -> node_modules/console-browserify/index.js -> ./node_modules/assert/build/assert.js -> ./node_modules/assert/../assertion_error.js -> ./node_modules/util/util.js
事实证明,util
在导出某些内容之前请求了 console-browserify
,而 assert
需要 util
导出内容,因此出现了这个错误。
而且,原来的 util.js
包根本不依赖于 console-browserify
,它是由 Webpack 通过以下方式注入的:
/* provided dependency */ var console = __webpack_require__(/*! ./node_modules/console-browserify/index.js */ "./node_modules/console-browserify/index.js");
我该如何解决这个问题?为什么 Webpack 会引入这种依赖?