How to solve circular dependency in Require.js?

后端 未结 1 1952
梦如初夏
梦如初夏 2021-02-06 06:44

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

相关标签:
1条回答
  • 2021-02-06 07:21

    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

    0 讨论(0)
提交回复
热议问题