It can be done. I've got one such plugin right here. Here's the general structure:
(function (factory) {
// If in an AMD environment, define() our module, else use the
// jQuery global.
'use strict';
if (typeof define === 'function' && define.amd)
define(['jquery'], factory);
else
factory(jQuery);
}(function ($) {
'use strict';
// This is the plugin proper.
$.fn.myMethod = function(/* ... */) {
// Code for the method...
};
}));
A plugin that needs other things than just jQuery would use the structure above with the following modifications:
A call to
define
that lists the additional modules needed.A
factory(jQuery)
call (in the non AMD branch, used when RequireJS is not loading the plugin) that passes additional values from the global space afterjQuery
.A factory function
function ($)
that has additional arguments to receive the additional values passed to it.
So if the plugin needs module foo
which exports itself in the global space as foo
and with a RequireJS configuration that names it "foo"
, then:
(function (factory) {
// If in an AMD environment, define() our module, else use the
// jQuery global.
'use strict';
if (typeof define === 'function' && define.amd)
define(['jquery', 'foo'], factory);
else
factory(jQuery, foo);
}(function ($, foo) {
'use strict';
// This is the plugin proper.
$.fn.myMethod = function(/* ... */) {
// Code for the method...
foo.blah();
};
}));