Reputation: 15646
I am learning jQuery and Backbone source code, and noticed they check if there is requirejs:
if ( typeof define === "function" && define.amd && define.amd.jQuery ) {
define( "jquery", [], function () { return jQuery; } );
}
if (typeof define === 'function' && define.amd) {
define(['underscore', 'jquery', 'exports'], function(_, $, exports) {
Why there always have a amd
property in define
function in requirejs?
And the define.amd
always is an object which key jQuery
is true
? Even I have not import the jQuery module?
Upvotes: 2
Views: 698
Reputation: 151441
It is a convention that AMD loaders should use to indicate that the define
they export into the global space is the define
that is made to be used by AMD modules to define themselves.
If AMD loaders did not use this convention then if some random JavaScript library decided to export a define
function into the global space that has nothing to do with AMD, then code which is designed to work with or without an AMD loader would erroneously believe that they are used in an environment where an AMD loader is present.
There is still a risk for things to go askew if some random third party library decided to also export its own define
function (that has nothing to do with defining AMD modules) and decided to add an amd
property to it, but the risk is much lower than if the scheme I explained above was not used.
So jQuery and Backbone in the code you've shown tests whether it is used in an AMD environment where an AMD loader is present, and if so defines itself as an AMD module.
define.amd.jQuery
is specific to jQuery and indicates that the loader is able to account for multiple version of jQuery being loaded simultaneously.
Upvotes: 2