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?
As per RequireJS API documentation, shim lets you. Configure the dependencies, exports, and custom initialization for older, traditional "browser globals" scripts that do not use define() to declare the dependencies and set a module value.
RequireJS is a JavaScript file and module loader. It improves perceived page load times because it allows JavaScript to load in the background. In particular, it enables asynchronous JavaScript loading.
Generally you only use RequireJS in its loading form during development. Once the site is done and ready for deployment, you minify the code. The advantage here is RequireJS knows exactly what your dependencies are, and thus can easily minify the code in the correct order.
jQuery uses shim configuration to define the dependencies for jQuery plugins and set a module value by declaring dependencies.
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) {
}
);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With