xhallix
xhallix

Reputation: 3011

Require JS, define dependencies only once

I wonder what is best practice to use standard dependencies with requireJS.

For example I have jquery, underscore and backbone as a dependency, I think I implemented them correctly in shim including their deps and make them work.

But what I think is not correct in my setting is, everytime I like to use those dependencies I have to the start the .js file with something like:

example.js

requirejs( ["jquery", "underscore", "backbone"], function(){
    //do stuff
});

So I would like to know, is it possible to use something like this:

foo.js

requirejs( ["jquery", "underscore", "backbone"], function(){
    //do stuff
});

bar.js

define(['public/foo'], function(){
    console.log(Backbone);
});

Or is it the normal way, that you have to define the same dependencies over and over again? Any guide would be really appreciated, because I cannot find something that answered my question.

Cheers

Upvotes: 1

Views: 89

Answers (1)

Yauheni Leichanok
Yauheni Leichanok

Reputation: 1769

libs.js

define(['jquery', 'underscore', 'backbone'], function($, _, Backbone) {
    return {
        $: $,
        _: _,
        Backbone: Backbone
    };
});

app.js

define(['libs'], function(Libs) {
    // now you can use any library you defined in libs.js

    Libs.$(function() {
        // the same as $(function() {});
    });
});

Upvotes: 3

Related Questions