I am reading some code which use requirejs to handle jquery.
It use
require([
'jquery',
],
function(
$
){} );
I am wondering why just using $ is enough for all jquery functions?
jQuery will define jquery module by itself if define function has already defined.
The following code is in jquery.js.
if ( typeof module === "object" && module && typeof module.exports === "object" ) {
// Expose jQuery as module.exports in loaders that implement the Node
// module pattern (including browserify). Do not create the global, since
// the user will be storing it themselves locally, and globals are frowned
// upon in the Node module world.
module.exports = jQuery;
} else {
// Otherwise expose jQuery to the global object as usual
window.jQuery = window.$ = jQuery;
// Register as a named AMD module, since jQuery can be concatenated with other
// files that may use define, but not via a proper concatenation script that
// understands anonymous AMD modules. A named AMD is safest and most robust
// way to register. Lowercase jquery is used because AMD module names are
// derived from file names, and jQuery is normally delivered in a lowercase
// file name. Do this after creating the global so that if an AMD module wants
// to call noConflict to hide this version of jQuery, it will work.
if ( typeof define === "function" && define.amd ) {
define( "jquery", [], function () { return jQuery; } );
}
}
Take a look at How to use RequireJS with jQuery.
But yes, you only need $ (witch is the same as jQuery) because every method (or plugin) jQuery provides is encapsulated inside that variable.
If you are using requirejs to load your files and you don't do it that way, $ will be undefined.
Example from the site:
require(['jquery'], function( $ ) {
console.log( $ ) // OK
});
require(['jquery'], function( jq ) {
console.log( jq ) // OK
});
require(['jquery'], function( ) {
console.log( $ ) // UNDEFINED!
});
$has lots of properties.