Documentation

You are viewing the documentation for the 2.2.1 release in the 2.2.x series of releases. The latest stable release series is 3.0.x.

§RequireJS

According to RequireJS’ website

RequireJS is a JavaScript file and module loader. It is optimized for in-browser use, but it can be used in other JavaScript environments, like Rhino and Node. Using a modular script loader like RequireJS will improve the speed and quality of your code.

What this means in practice is that one can use RequireJS to modularize big javascript codebases. RequireJS achieves this by implementing a semi-standard API called Asynchronous Module Definition (other similar ideas include CommonJS ). Using AMD it’s possible to resolve and load javascript modules, usually kept in separate files, at client side while allowing server side optimization, that is, for production use, dependencies can be minified and combined. Therefore, RequireJs supports both client side and server side resolutions.

RequireJs support is enabled by default, so all you need to do is to drop javascript modules into public/javascripts and then bootstrap the module using one of the preferred RequireJS bootstraping techniques.

§Things to know about the implementation

§Example

create app/assets/javascripts/main.js:

require.config({
    paths: {
        'thirdParty': 'path/to/lib'
    }
});


require(["helper/lib","thirdParty"],function(l,t) {
	var s = l.sum(4, 5);
	alert(s);
});

create app/assets/javascripts/helper/lib.js:

define(function() {
    return {
         sum: function(a,b) {
    		return a + b;
        }
    }
});

create app/views/index.scala.html:

@helper.requireJs(core = routes.Assets.at("javascripts/require.js").url, module = routes.Assets.at("javascripts/main").url)

In your build.sbt add:

requireJs += "main.js"

requireJsShim += "main.js"

After rendering the page in Dev mode you should see: 9 popping up in an alert

§When running stage, dist or start

your application’s jar file should contain (public/javascripts-min/main.js):

define("helper/lib",[],function(){return{sum:function(e,t){return e+t}}}),require(["helper/lib"],function(e){var t=e.sum(5,4);alert(t)}),define("main",function(){})