Circular Dependencies in modules using requireJs

前端 未结 3 1042
执念已碎
执念已碎 2021-01-04 20:47

Reading the requireJs documentation,
in order to fix the Circular Dependencies, is suggested to use exports to create an empty object for the module that is

3条回答
  •  抹茶落季
    2021-01-04 21:36

    I often have circular issues using AMD modules to build an application core that both stands up many modules and contains config or other useful objects for those modules to use.

    I did some experimenting today and this seems to work pretty well.

    define(['exports', 'underscore', './config', './mediator'],
      function (exports, _, Backbone, config, Mediator){
    
        Core = /* ... */
    
        // Publicize a core 'singleton' so that it's dependencies can access it, and so can modules that define it as a dependency themselves.
        core = new Core()
        exports.core = core //publicize it in a way that supports circularity
        return core // And also publicize it normally
      }
    )
    

    The objects are both '===' equal to each other, so this seems very promising.

    EDIT:

    The above method doesn't work when optimized. Here's another method that may (untested): https://github.com/requirejs/example-multipage/blob/master/www/js/app/main1.js#L2

    define(function (require) {
      var $ = require('jquery'),
          lib = require('./lib'),
          Core;
    
       Core = /* ... */
    
       return new Core()
    });
    

提交回复
热议问题