WebJars Locator now has direct support for RequireJS! For a while the WebJars Play helper library has had support for RequireJS which was great but it had a few issues and wasn’t useful outside of Play.
There is now a org.webjars.RequireJS.getSetupJavaScript(String webjarUrlPrefix)
method that produces the RequireJS configuration for the WebJars you are using. If you are using only the jQuery WebJar then that JavaScript configuration looks like:
var webjars = {
versions: { 'requirejs': '2.1.10', 'jquery': '2.1.0' },
path: function(webjarid, path) {
return '/webjars/' + webjarid + '/' + webjars.versions[webjarid] + '/' + path;
}
};
var require = {
callback: function() {
// no-op webjars requirejs plugin loader for backwards compatibility
define('webjars', function () {
return { load: function (name, req, onload, config) { onload(); } }
});
// all of the webjar configs from their webjars-requirejs.js files
// webjar config for jquery
requirejs.config({
paths: { "jquery": webjars.path("jquery", "jquery") },
shim: { "jquery": { "exports": "$" } }
});
}
}
This sets up the paths for RequireJS modules in WebJars and pulls in any other custom configuration from the WebJar’s RequireJS config. To use this setup JavaScript with RequireJS you can add something like the following to your web page: