1
votes

I'm working on the project that uses require.js and I was faced with a simple question about declaring libraries as dependencies within every single modules. I saw many examples with require.js and in every of them libraries like Backbone, jquery, underscore etc was declared in every module. And it would be fine if your application consists of only couple of modules. But if your application has 40-50 modules it becomes a bit tedious to define jquery every single time.

On the other hand we can load all libraries into the require() this way:

// Just an example
require.config({
    paths: {
        jquery: '../bower_components/jquery/jquery',
        underscore: '../bower_components/underscore/underscore',
        backbone: '../bower_components/backbone/backbone'
    }
});

require(['jquery', 'underscore', 'backbone'], function () {
    require([
        'app',
        'bootstrap'
    ], function (App) {
        var app = new App();
        document.body.appendChild(app.el);
    });
});

And then we can use Backbone, '_' and '$' into the App without declaring them as dependencies.

So I'm trying to understand why we should define them every time. Is it just a strict adherence to the Module pattern or something else?

Thanks.

1
I'd say that requiring the dependencies to be (painfully) explicit is one of the main benefits of AMD modules. Looking at dependencies is a good litmus test: if there are too many per module or they are on different levels of abstraction (e.g. Backbone and jQuery always appear together) it may be a sign that you should consider splitting things up and/or making the layers more distinctive.kryger

1 Answers

3
votes

Having your libraries passed in as arguments to your require factory function is a form of dependency injection. Now, depending on exactly how AMD-friendly your library dependencies are, you may even be able to use several different versions of the library at once in an application. Writing your modules in this way with explicit library dependencies can allow you future flexibility of mixing modules which require jQuery 1.8 and jQuery 2.0, for instance. A different jQuery version can be passed to each module.

When you don’t define all your dependencies explicitly every time, then you’re relying on the global variable (window.$ or window._) created as a side effect of loading the library. In that case, all the modules have to depend on the same version of the library.