简体   繁体   中英

Dynamic exports in an AMD module

Does AMD allow you to define a module whose exports are dynamic, depending on other modules?

The problem I have is that define immediately returns, even if there are require calls in the body. This means that, if the module's definition depends on other modules, any module depending on it cannot be sure the module is fully loaded, even though the dependency is fulfilled.

Some code to explain my problem:

// A module that exports one function 'f'. The implementation of this f comes
// from another module, dynamically selected based on a condition.
define("mymodule", function (require, exports) {
  var functionImplModule = someCondition ? "function-impl1" : "function-impl2";
  require([functionImplModule], function (functionImpl) {
    exports.f = functionImpl;
  });
});

// Entry point. I want to use module.f in some code.
require(["mymodule"], function (mymodule) {
  // Can't use mymodule.f here yet, because the require() of 'mymodule' isn't done yet
  console.log(mymodule.f);
});

Can this be done in AMD? Or how is code like this better structured?

I would return a promise in your exports .

define("mymodule", function (require, exports) {
  var deferred = ..., functionImplModule = someCondition ? "function-impl1" : "function-impl2";
  require([functionImplModule], function (functionImpl) {
        deferred.resolve(functionImpl);
      });

  exports.f = deferred.promise;
});

// Entry point. I want to use module.f in some code.
require(["mymodule"], function (mymodule) {
   mymodule.f.then(function(impl) ... );
});

Please note It also appears that you are lazy configuring your module as well. This isn't good for bundling and minification. Perhaps you could use your config to change the which file is used for mymodule .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM