How to solve circular dependency in Require.js?

pilau picture pilau · Jun 17, 2013 · Viewed 8.1k times · Source

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 utilities from "main":

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

    tools.subModule = sub;

    return tools;
});

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

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

How can I achieve this with require.js without creating a black hole that would swallow the whole planet?

Thank you very much.

Answer

freejosh picture freejosh · Jun 17, 2013

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