Reputation: 12295
I have written a jQuery plugin using require, wrapped it in almond, and loaded it through a shim config in another app. Unfortunately, require is exposing the global jQuery to the plugin rather than the local one. My code:
(function() {
// almond code
// other dependencies
require(dependencies, function (dependencies) {
!function($) {
// window.jQuery == $ -> true
$.fn.plugin = function(options) { return this; }
}(jQuery);
});
})();
require.config({
paths: { 'jquery': 'vendor/jquery-1.9.1.min' },
shim: { 'plugin': ['jquery'] }
});
require(['jquery','plugin'], function ($) {
// window.jQuery == $ -> false
$('#plugin').plugin(options);
// error, object [Object object] has no method "plugin"
);
Shouldn't shim load the plugin code exposing the local jQuery module to the plugin's global scope?
Upvotes: 2
Views: 1232
Reputation: 19377
I believe the problem is that you are trying to use shim
with AMD modules, when really that feature is designed for non-AMD modules. From that section of the documentation:
Remember: only use shim config for non-AMD scripts,scripts that do not already call define(). The shim config will not work correctly if used on AMD scripts, in particular, the exports and init config will not be triggered, and the deps config will be confusing for those cases.
If you want to keep jQuery out of global scope and still use it with your other modules, you can follow the Mapping Modules to use noConflict approach:
If all of your modules (including any third party jQuery plugins or library code that depend on jQuery) are AMD compatible and you want to avoid having $ or jQuery in the global namespace when they call require(['jquery']), you can use the map config to map the use of jQuery to a module that calls noConflict and returns that value of jQuery for the 'jquery' module ID.
See also Using private jquery with RequireJS - issue after optimisation for a step-by-step example.
Upvotes: 3