Official Support for RequireJS in WebJars

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:

<!-- The following can use the WebJars Locator to avoid hard-coding the full path -->

The WebJars Play library now has a new helper that wraps all that up into a nice function:

@Html(org.webjars.play.RequireJS.setup("index"))

That loads the setup JavaScript and loads RequireJS with the right data-main. Check out a full example of this with AngularJS in the Play Angular Seed Activator template.

Now using RequireJS is just normal syntax (no more webjars! prefix), like:

require(["jquery"], function(jquery) {
    console.log(jquery)
});

All of this was added very recently so make sure you are using at least webjars-locator version 0.12 and webjars-play version 2.2.1-2. Also this change may cause some incompatibilities in the WebJar RequireJS config files (webjars-requirejs.js) so if you experience strange behavior please file an issue on the WebJar.

Let me know how it goes!