jQuery 1.7+, AMD (RequireJS), and Global Scope

2019-05-28 08:49发布

问题:

I'm trying to get more in line w/ AMD, and I've come across something in jQuery source that I just can't quite undertand.

Here is section (found just before the end of the file):

if ( typeof define === "function" && define.amd && define.amd.jQuery ) {
    define( "jquery", [], function () { return jQuery; } );
}

From what I can see, one of the major points of AMD is to keep the global scope clean. Yet jQuery chooses to return a reference to itself as a module, but still infects the global space.

It seems to me, that adding "jQuery.noConflict();" just before the return would resolve this and still return the object as a module.

I know that RequireJS has some special files specifically for jQuery, but I'm not sure that it's needed for 1.7+.

My question is 2 part:

1) Does anyone know why this decision was taken?

2) Since this approach is not upgrade friendly, is anyone familiar with a more elegant solution that utilizes the standard version of RequireJS and jQuery?

回答1:

Ok, just after posting, I just realized I could proxy it through another file:

//main.js
require.config({
    paths : {
    jquery : 'my/libs/jquery-1.7.1.min',
    jQuery : 'my/src/jquery'
}

and

//my/src/jquery.js

define([
        'jquery'
    ],
    function($) {
        $.noConflict(true);

        return $;
    }
);

The reason for the 'jquery' alias for the main file rather than just reference the fully qualified location in the proxy is because I'm using an AMD-ready branch of Backbone that depends on this alias:

https://github.com/jrburke/backbone/blob/2b0cfb4282f071cffb14a9573d703da6acc5febd/backbone.js

The author has had some commits accepted by Document Cloud and is hoping that this modification gets drawn in too.

It will be interesting to see if there are any flaws with this or what additional answers there could be from the AMD battle tested.