问题描述:

The line $("body").slimScroll(); throws error, because slimScroll is not defined. That is because require.js probably doesn't load automatically shim keys, if you are requiring any module, that is specified as dependency in shim (i think if i have shim jquery.slimscroll and its dependency is jquery, then when i require jquery, it automatically loads jquery.slimscroll - this behavior doesn't happen).

So the right way is call define(['jquery', 'jquery.slimscroll') function ($) ..., so require knows i need jquery.slimscroll and because it is in shim, it will be loaded a bit different, because it is not AMD compatible.

Problem is that if i have lot of jquery plugins, i need always pass all plugins that i need in define call. Is there any way, how to solve this type of annoying behavior and write just define(['jquery'], function ($) ..?

require.config({

baseUrl: 'js/bower',

paths: {

react: 'react/react-with-addons',

jquery: 'jquery/dist/jquery',

'jquery-private': '../jquery-private',

'jquery.slimscroll': 'jquery-slimscroll/jquery.slimscroll.min'

},

map: {

'*': {

jquery: 'jquery-private',

},

'jquery-private': {

jquery: 'jquery'

}

},

shim: {

'jquery.slimscroll': ['jquery']

}

});

require(['jquery'], function ($) {

$("body").slimScroll();

});

网友答案:

You could just add the jquery plugins to the dependencies of your jquery-private module.

define(['jquery', 'jquery.slimscroll', ...], function (jQuery) {
    return jQuery.noConflict(true);
});

This way, when any module requires jquery, the plugins are also loaded at the same time.

I'm assuming that jquery-private is meant to load jQuery so that it does not conflict with other version of jQuery. That's what my example reflects above but it does not generally matter what the module actually does.

With this method you still need to have a shim configuration for each plugin that is not an AMD module. Moreover, your plugins will have to get a map setting just like for jquery-private to get the real jquery module. Otherwise, there will be a circular dependency.

相关阅读:
Top