backdesk
backdesk

Reputation: 1781

RequireJS - Managing Modules Centrally

Maybe I missed this in the documentation somewhere but here goes. I've got a core controller that takes care of managing modules. I have about 20 modules so far and would like to be able to easily configure them to be loaded by the core. This means I have a large array or lots of calls to require. Is it acceptable/good practise to create a list of modules in a literal object and then have a module load it's dependencies from that? Here's an example of what I mean:

Config.js

modules = [
    'moduleA',
    'moduleB',
    'moduleC'
];

Core.JS

define(
    ['config'],
    function(config) {
        // Somewhere in here I parse the list and require() each one ?   
        return {
            startAll : function() {
                console.log('starting all modules.');

                // Then call a method common to all 'modules' in the list above.
            }
        }
    };
  }
);

I'm not sure if this is such a good idea as I'm new to RequireJS but I like the idea of being able to configure which modules are loaded from one place. In my case by module I am referring to UI widgets that I have written more specifically.

Upvotes: 5

Views: 263

Answers (1)

I've solved the same issue by using a "package" pattern of sorts. Basically the package acts as a facade for my widgets. To give you a better idea of what I'm talking about, consider this:

widgets.js:

define(['./widgets/button', ...], function(button) {
    return {
        button: button, // expose the widgets here
        ...
    }
});

In this case the button module just returns a function. You might need to tweak the facade to fit your case.

This scheme makes it possible to refer to the widgets simply by importing the facade. In my case this was highly beneficial. I use the same idea in some other places too to wrap modules up and to make them easier to use.

You'll lose some of the benefits of RequireJS by doing this, though. This will load all the widgets in any case even if you don't happen to need some at the moment. Of course in that case you can just update the facade but it's extra work...

Upvotes: 3

Related Questions