Question

I'm new to AMD and loaders like require.js, but so far I've been under the assumption that a properly structured require.js project does not create any global variables. How come a script like jQuery can be loaded via require.js and appear to be AMD-compliant, but it still creates a global $ variable?

Am I misunderstanding what AMD compliant means or how it works? I'm looking into writing my own AMD-compliant modules but I want to make sure I'm doing things the proper way...

requirejs.config({
    baseUrl: 'js',
    paths: {
        "jquery": "//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.0/jquery.min"
    }
});

require(["jquery"], function(jquery) {
    console.log(jquery);
    console.log($); // This works, but I wouldn't expect it to.
});
Était-ce utile?

La solution

JQuery creates the global $ variable because JQuery is not designed to be an AMD module, although it does support it. You can wrap JQuery to remove the global $ scope as described here, if you read the section on JQuery it explains the reasons why the global variable is there. I remember doing this when I first started using requirejs but it caused some problems with plugins ... as I remember

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top