Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

require.js jQuery noConflict shim - Why is init method never called

I want to get rid of the global jQuery objects (window.$ and maybe also window.jQuery).

data-main:

require.config({
    paths: {
        "jquery": "jquery-2.0.0"
    },
    shim: {
        "bootstrap": {
            deps: ["jquery"]
        },
        "jquery": {
            deps: [],
            init: function() {
                return this.jQuery.noConflict(true);
            },
            exports: "jQuery"
        }
    }
});

require(["jquery", "bootstrap"], function($) {
    // ...
});

What's wrong with this code? "init" is never called.

like image 850
bert Avatar asked Feb 17 '23 10:02

bert


2 Answers

The recently-updated Use with jQuery page on the RequireJS site explains more about why this happens and what you can do to resolve it. Here is the relevant part:

jQuery registers itself as the global variables "$" and "jQuery", even when it detects AMD/RequireJS. The AMD approach advises against the use of global functions, but the decision to turn off these jQuery globals hinges on whether you have non-AMD code that depends on them. jQuery has a noConflict function that supports releasing control of the global variables and this can be automated in your require.config, as we will see later.

And if you want to suppress these global functions, you need to use a map config to a noConflict wrapper module rather than a shim config. As @tomaskirda pointed out, jQuery doesn't fire shim.init for libraries that support AMD. The relevant code from the Use with jQuery page:

require.config({
    // Add this map config in addition to any baseUrl or
    // paths config you may already have in the project.
    map: {
      // '*' means all modules will get 'jquery-private'
      // for their 'jquery' dependency.
      '*': { 'jquery': 'jquery-private' },

      // 'jquery-private' wants the real jQuery module
      // though. If this line was not here, there would
      // be an unresolvable cyclic dependency.
      'jquery-private': { 'jquery': 'jquery' }
    }
});

// and the 'jquery-private' module, in the
// jquery-private.js file:
define(['jquery'], function (jq) {
    return jq.noConflict( true );
});
like image 136
explunit Avatar answered Feb 19 '23 02:02

explunit


It is not called most likely because jQuery implements AMD module and there is no need for shim.

like image 25
Tomas Kirda Avatar answered Feb 19 '23 02:02

Tomas Kirda