Search code examples
javascriptrequirejsjs-amd

RequireJs define default deps


usually a requirejs module looks like:

define('ModuleName', ['jquery', 'underscore', 'backbone'], function($, _, Backbone){

});

because every file in my setup requires underscore and backbone I would like to have them automaticly available in the module without having to define them as dependencies.

So something like:

define('ModuleName', ['jquery'], function($){
    $("div.someClass").addClass('hide'); // works
    var Model = Backbone.Model.extend(); // works too
});

Is this possible?

If yes how or what is the keyword I have to look for?


Solution

  • The modules you're interested in would have to be attached to an outer scope. By default, Backbone, Underscore, jQuery etc remain attached to the global scope unless you call noConflict() on them (not all modules provide this nicety). Attaching your modules to the global scope isn't a great solution, but would accomplish what you're asking for and is the default behavior anyway. The better alternative would be to define an outer module (or just a require() call) which contains those dependencies in addition to your named sub-modules. Otherwise, much of the reason for using RequireJS is lost.

    Edited for example:

    require(['underscore', 'backbone'],
        function (_, Backbone) {
            define('ModuleName', ['jquery'], function($){
                $("div.someClass").addClass('hide'); // works
                var Model = Backbone.Model.extend(); // works too
             });
    
            //Other modules here, otherwise this is pointless too
        }
    );
    

    Even this is only useful if you're defining multiple named modules in the same file. The best solution from my perspective is unfortunately to explicitly import your modules and allow implicit module naming, but the above example is the closest to what you're asking for. As for implicit module names, from the RequireJS api docs:

    You can explicitly name modules yourself, but it makes the modules less portable -- if you move the file to another directory you will need to change the name.