Search code examples
amdcircular-dependencycurl.js

How do I make curl.js resolve circular dependencies?


I've got two AMD modules which should reference each other, but as soon as I add backward dependency, it stops working. I suppose it got stuck in waiting state.

index.html:

<!DOCTYPE html>
<html>
  <head>
    <script src="/curl.js"></script>
  </head>
  <body>
    <script>
      curl(['m1', 'm2'], function(m1, m2) {
          console.log('done', m1, m2);
      });
    </script>
  </body>
</html>

m1.js:

define(['m2'], function() {
    return 1;
});

m2.js

define(['m1'], function() {
    return 2;
});

Solution

  • UPD It appears I was wrong and curl.js doesn't always resolve circular dependencies.


    You should declare it in CommonJS way:

    index.html:

    <!DOCTYPE html>
    <html>
      <head>
        <script src="/curl.js"></script>
      </head>
      <body>
        <script>
          curl(['m1', 'm2'], function(m1, m2) {
              console.log('done', m1.v, m2.v);
          });
        </script>
      </body>
    </html>
    

    m1.js:

    define(function(require, exports) {
        var m2 = require('m2');
        exports.v = 1;
    });
    

    m2.js

    define(function(require, exports) {
        var m1 = require('m1');
        exports.v = 2;
    });
    

    Another option is to mix the approaches (AMD, CommonJS):

    m1.js:

    define(function(require) {
        var m2 = require('m2');
        return 1;
    });
    

    UPD But there might be some problems. I haven't yet figured out what's happening. I've created an issue for one of them for now.