Is there a way to define a module that "dynamically" load other modules in RequireJS? If yes, how the optimizer (r.js) understands how/when a module has to be included?
For example, let dynModules
a module which defines name/path pairs:
define([], function () {
return ['moduleA', 'moduleB']; // Array of module names
});
Another module is going to load modules dynamically, based on the array. This will not work:
define(['dyn_modules'], function (dynModules) {
for(name in dynModules) {
var module = require(path); // Call RequireJS require
}
// ...
});
... gives me:
Uncaught Error: Module name "moduleA" has not been loaded yet for context: _. Use require([]) http://requirejs.org/docs/errors.html#notloaded
I can solve the error, but it's not "dynamic" anymore:
define(['dyn_modules', 'moduleA', 'moduleB'], function (dynModules) {
for(name in dynModules) {
var module = require(path); // Call RequireJS require
}
// ...
});
This question is related to
javascript
browser
module
requirejs
r.js
Answering to myself. From the RequireJS website:
//THIS WILL FAIL
define(['require'], function (require) {
var namedModule = require('name');
});
This fails because requirejs needs to be sure to load and execute all dependencies before calling the factory function above. [...] So, either do not pass in the dependency array, or if using the dependency array, list all the dependencies in it.
My solution:
// Modules configuration (modules that will be used as Jade helpers)
define(function () {
return {
'moment': 'path/to/moment',
'filesize': 'path/to/filesize',
'_': 'path/to/lodash',
'_s': 'path/to/underscore.string'
};
});
The loader:
define(['jade', 'lodash', 'config'], function (Jade, _, Config) {
var deps;
// Dynamic require
require(_.values(Config), function () {
deps = _.object(_.keys(Config), arguments);
// Use deps...
});
});
Source: Stackoverflow.com