circular imports with webpack returning empty object

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

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)