Search code examples
requirejsamd

RequireJS Multi Injecting


I am building a modular single page application which consumes multiple require config files from different sources. I would like a way in my application to be able to consume a list of all modules of a specific type. something like this:

define('module-type/an-implementation',...)
define('module-type/another-implementation',...)

require('module-type/*', function(modules){
    $.each(modules,function(m){ m.doStuff(); });
})

This is similar patterns dependency injectors use with multiple dependency injection (eg. https://github.com/ninject/ninject/wiki/Multi-injection)

Is there a way to do this (or something similar) with require?


Solution

  • RequireJS doesn't know which modules exist until something requires them. Once a module is required / depended upon RequireJS will figure out where to request the module from based on module's name and RequireJS's configuration. Once the module is loaded it can be examined / executed to find out its dependencies and handle them in turn, until all dependencies are loaded and all module bodies are executed.

    In order to be able to "consume a list of all modules of a specific type" something would need to be able to find all such modules. RequireJS doesn't have any means to know which modules exist, so it alone wouldn't be enough to implement "Multi Injection".

    Speculation

    Some kind of module registry could be created and populated with help of the build system: e.g. a file (say module-registry.js) could be generated each time a file in the source directory is added / removed or renamed, then multi inject could be possible like:

    multiRequire('module-type/*', function(modules){
        $.each(modules,function(m){ m.doStuff(); });
    })
    

    which in turn would call

    require(findModules(pattern), function() {
        callback(Array.prototype.slice.call(arguments, 0));
    });
    

    (where multiRequire and findModules are provided by the module registry).