RequireJs: Use autoloading-deps with shim

10,418

Solution 1

Remove the $, _, Backbone-parameters from the require-function where you extend the Router. The shims export global values, so there is no need to reference to them in require or define calls like you do for regular dependencies.

Passing them as parameters messes with the global variables and most likely results in them being undefined.

Solution 2

From what I've read, requirejs passes arguments based on what you specify in the array... Thus your call should look like this:

require(["app"], function (App) { // less arguments
});

Or like this:

require(
    ["jquery", "underscore", "backbone", "app"], // more deps
    function ($, _, Backbone, App) {
    }
);
Share:
10,418
dev.pus
Author by

dev.pus

Updated on June 25, 2022

Comments

  • dev.pus
    dev.pus almost 2 years

    I have defined a RequireJs configuration which defines paths and shims:

    require.config({
        // define application bootstrap
        deps: ["main"],
    
        // define library shortcuts
        paths: {
            app: "app"
            , jquery: "lib/jquery"
            , underscore: "lib/underscore"
            , backbone: "lib/backbone"
            , bootstrap: "lib/bootstrap"
        },
    
        // define library dependencies
        shim: {
            jquery: {
                exports: "$"
            },
            underscore: {
                exports: "_"
            },
            backbone: {
                deps: ["underscore", "jquery"],
                exports: "Backbone"
            },
            bootstrap: {
                deps: ['jquery'],
                exports: "bootstrap"
            },
    
            // main application
            app: {
                deps: ["backbone"],
                exports: "App"
            }
        }
    });
    

    As you see the last "shim" declaration should make it able to access backbone (and it deps) when I load the main App(-namespace).

    In reality this doesn't work:

    require(["app"], function($, _, Backbone, App){
        app.router = new Backbone.Router.extend({
            // routing and route actions
        });
    });
    

    What makes me wondering is that in the "backbone-boilderplate"-project, Backbone (and its deps) are available this way: https://github.com/tbranyen/backbone-boilerplate/blob/master/app/main.js

    The not even had to define this in the function.

    So what am I doing wrong?