Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
330 views
in Technique[技术] by (71.8m points)

javascript - 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

When I run the code, I get an error in File C:

A.doSomething is not a function

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is not a webpack issue but a property of CommonJS modules.

When a CommonJS module is first required, its exports property is initialized to an empty object behind the scenes.

module.exports = {};

The module can then decide to extend this exports property, or override it.

exports.namedExport = function() { /* ... */ }; // extends

module.exports = { namedExport: function() { /* ... */ } }; // overrides

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';

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...