45

Is there any way to access all loaded modules of require.js?

Background:
I want to automatically call an init() function of my javascript-modules after all of them are loaded, see require.js + backbone.js: How to structure modules that have an initialize function? Without require.js I looped over my own module-storage and called each init() function.
I now want to do this with require.js. I'm aware that calling a my_custom_init_function_favoritecolor_petname_love123 of every loaded module (including external libraries) is dangerous. I hope that this will cause less trouble than manually keeping a list of all modules (and the requirements of these modules) up-to-date. Forgetting one module init() is much more likely than a third-party library having my custom function name (though the latter is probably harder to debug).

Or does anyone have a better idea of how to accomplish that?

Community
  • 1
  • 1
Michael
  • 731
  • 1
  • 7
  • 11

3 Answers3

72

Yes, require.s.contexts._.defined is an object which its keys are the module names and the values include the value returned from that module.

require.s.contexts._.defined includes all the modules (either define() or require() such as the Javascript file that is the starting point of the program and is indicated using data-main for RequireJS).

AlexStack
  • 16,766
  • 21
  • 72
  • 104
  • 5
    What is the difference between registry and defined on the context? I see a new object on the context._.registry object after a define('Mod',...), but not on context._.defined. After a require(['Mod'],...) call I see the module on context._.defined. – alexK85 May 29 '14 at 04:37
  • 1
    Cannot read property 'contexts' of undefined. Require is the method, so switching to this worked for me requirejs.s.contexts._.defined – Tyguy7 Nov 18 '19 at 01:04
11

Just finished a similar behavior within my RequireJS project. require.s.contexts['_'].registry holds the list of the registered modules.

I am using Underscore.js for getting, filtering and iterating the list of modules. Maybe the following code fragment helps you:

var modules_registered = _.keys(require.s.contexts['_'].registry);
var modules_to_be_initialized = _.filter(modules_registered, function(module_title) {
    return module_title.indexOf('modules') > -1;
});

_.each(modules_to_be_initialized, function(module_name) {
    require([module_name], function(current_module) {
        current_module.init();
    });
});
Volker Rose
  • 1,808
  • 15
  • 16
1

I'm lazy, so I just did this:

    var modulesToLoad = Object.keys(require.s.contexts['_'].registry);
    require(modulesToLoad);

Based on other answers here.

Zar Shardan
  • 5,675
  • 2
  • 39
  • 37