I'm wondering why can't I use the require() function with something like this:
// I'm using define's sugar syntax
define(function(require) {
// This works fine. It assigns myModule to the myModule variable (no callback needed)
var myModule = require('myModule');
var getModule = function(name) {
// This doesn work. Using require() here expects a callback
return require(name);
};
return getModule;
});
That second require() call throws (but taking a look with DevTools shows that <name> is actually loaded):
Uncaught Error: Module name <name> has not been loaded yet for context: _
Why does the first require() call just returns the module (no need to do it in a callback fashion), but the second require() call only works with a callback?
requireso it can build a dependency tree. In order to do that, it needs to know up front all the dependencies of a given module. It can't do that dynamically because it needs to know every dependency before it actually fetches anything.