Reputation: 148
RequireJS provides a shim configuration for loading traditional/legacy libraries which do not support AMD. The shim config allows exporting the said library to a variable.
'backbone' : {
deps : ['underscore', 'jquery'],
exports : 'Backbone'
}
As shown above, Backbone is not AMD compatible hence the shim config is used to export the library to a variable. Similarly this can be done for Underscore.
'underscore' : {
exports : '_'
}
But even if we do not specify the shim config for Underscore, it still works fine. How ? Can someone please shed some insight on this ?
Upvotes: 2
Views: 1815
Reputation: 6004
Backbone has a dependency of underscore. Its not necessary that this dependency has to be obtained with require and other things such as shim.
Backbone only expect _ to be there in global namespace containing interface to underscore library.
When you require backbone, we as app developer provide the dependencies using shim option with deps property to tell about what all dependencies are there for this particular module.
exports property is only a way to tell require to use a property from global namespace when referring to non AMD module, such as backbone or _.
So to answer your question. If you do not provide the shim config for underscore your following line will fail.
var _ = require('underscore');
variable _ in local namespace will be undefined in this case, and backbone will be using _ from the global namespace.
To answer your doubt. How does it work in backbone source.
// Require Underscore, if we're on the server, and it's not already present.
var _ = root._;
if (!_ && (typeof require !== 'undefined')) _ = require('underscore');
Above is extract of backbone source where it requires underscore. Its evident from comments above that this require is for server side. root object when in browser refers to window. So your first check "!_" returns false when in browser cause _ is available in gloabl object aka window. So the require doesn't happens in browser(if underscore already present).
Upvotes: 3
Reputation: 4479
It works because underscore defines global variable _
that is used in Backbone, and shim config for Backbone correctly sets dependencies so underscore and jquery are loaded before Backbone.
But it shouldn't work if you don't have shim config for underscore and then try to import it in your module:
define(['underscore'], function(_) {
})
Upvotes: 2