Skip to content Skip to sidebar Skip to footer

How To Solve Circular Dependency In Require.js?

Basically, the idea is that 'sub' module creates an object, and that object should be part of a utilities library which is the 'main' module. However, the 'sub' object depends on u

Solution 1:

There are a few things suggested in the docs:

b can fetch a later after modules have been defined by using the require() method (be sure to specify require as a dependency so the right context is used to look up a)

e.g.:

// Sub module
define(['require'], function(require) {
    return new (function () {

        // Singleton object using functions in main module
        var somestuff = function () {
            require('main').utilityMain();
            // etc
        };
    })();
});

or

you could instead use exports to create an empty object for the module that is available immediately for reference by other modules

e.g.:

// Main module
define(['sub', 'exports'], function(sub, exports) {
    exports.utilityMain: function () {
       // ...
    };

    exports.subModule = sub.sub;
});
// Sub module
define(['main', 'exports'], function(main, exports) {
    exports.sub = new (function () {

        // Singleton object using functions in main module
        var somestuff = function () {
            main.utilityMain();
            // etc
        };
    })();
});

and

Circular dependencies are rare, and usually a sign that you might want to rethink the design


Post a Comment for "How To Solve Circular Dependency In Require.js?"