RequireJs: Use autoloading-deps with shim

2019-03-27 07:55发布

问题:

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?

回答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.



回答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) {
    }
);