interlockjs / interlock

JS bundler - inspired by Git, built on Babel.
MIT License
72 stars 7 forks source link

Asynchronous module loading #30

Open divmain opened 9 years ago

divmain commented 9 years ago

Add feature similar to require.ensure, but call it require.async.

const libA = require("./lib-a");
require.async(["./lib-b", "./lib-c"], function (libB, libC) {
  // ...
});

Example output

{
  'aaaaaa': {
    deps: [],
    fn: function (require, module, exports) {
      var libA = require("bbbbbb")
      require.async("cccccc"/*["dddddd", "eeeeee"]*/, function (libB, libC) {
        // ...
      });
    }
  },
  'bbbbbb': {
    deps: [],
    fn: function (require, module, exports) {
      module.exports = "libA";
    }
  },
  'cccccc': {
    deps: ["dddddd", "eeeeee"],
    fn: function (require, module, exports) {
      module.exports = function (cb) {
        cb(require("dddddd"), require("eeeeee"));
      };
    }
  },
  'dddddd': {
    deps: [],
    fn: function (require, module, exports) {
      module.exports = "libB";
    }
  },
  'eeeeee': {
    deps: [],
    fn: function (require, module, exports) {
      module.exports = "libC";
    }
  }
}

When the require.async is invoked within the example module, the Interlock will call the cccccc module as if it were an entry point - first ensuring that all dependencies are installed and invoked, resolving/installing/invoking any missing dependencies, and finally calling the cccccc module itself. This module's exports will be a function that invokes a callback, requiring and passing constituent dependencies as parameters.

The require.async implementation will have recorded the callback passed to it, and pass that to cccccc's returned function when available.