使用 webpack 返回空对象的循环导入 [英] circular imports with webpack returning empty object
问题描述
目前正在解决这个确切的问题:
Hitting this exact problem currently:
FileA:
var b = require file B
var c = require file C
FileB:
var a = require file A
FileC:
var a = require file A
当我运行代码时,我在文件 C 中收到一个错误:
When I run the code, I get an error in File C:
A.doSomething is not a function
在那里扔了一个调试器,看到 A 是一个空对象.真正奇怪的是,我只在文件 C 中收到错误,而在文件 B 中没有收到错误.这里超级困惑.
Threw a debugger in there and saw that A is an empty object. What's really weird is that I'm only getting an error in File C, but not File B. Super confused here.
推荐答案
这不是 webpack 的问题,而是 CommonJS 模块的一个属性.
This is not a webpack issue but a property of CommonJS modules.
当第一次需要一个 CommonJS 模块时,它的 exports
属性在后台被初始化为一个空对象.
When a CommonJS module is first required, its exports
property is initialized to an empty object behind the scenes.
module.exports = {};
然后模块可以决定扩展这个 exports
属性,或者覆盖它.
The module can then decide to extend this exports
property, or override it.
exports.namedExport = function() { /* ... */ }; // extends
module.exports = { namedExport: function() { /* ... */ } }; // overrides
所以当 A
需要 B
并且 B
需要 A
时,A
> 不会再次执行(这会产生无限循环),但会返回其当前的 exports
属性.由于 A
在文件的最顶部需要 B
,在导出任何内容之前,require('A')
在 中调用B
模块将产生一个空对象.
So when A
requires B
and B
requires A
right after, A
is not executed again (which would produce an infinite loop), but its current exports
property is returned. Since A
required B
at the very top of the file, before exporting anything, the require('A')
call in the B
module will yield an empty object.
循环依赖的常见修复方法是将导入放在文件末尾,在导出其他模块所需的变量之后.
A common fix for circular dependencies is to put your imports at the end of the file, after you've exported the variables needed by other modules.
A
:
module.exports = { foo: 'bar' };
require('B'); // at this point A.exports is not empty anymore
B
:
var A = require('A');
A.foo === 'bar';
这篇关于使用 webpack 返回空对象的循环导入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!