Saturday, November 17, 2012

How to run and build an AMD application using r.js

Here is an AMD application that adds two numbers together.  1 and 2. 

It assumes you have git shell, node.js and r.js installed.  I followed the recommended layout for installing r.js:

mkdir requirejs 
cd requirejs 
git clone git://github.com/jrburke/r.js.git 
git clone git://github.com/jrburke/requirejs.git 
git clone git://github.com/requirejs/text.git

I then created three files that make my AMD calculator application:
  1. addop.js
  2. calc.js
  3. app.js

addop.js
define([], function() {
    return function (a, b) { return a + b; }
});


calc.js
define(["addop"], function (addOp) {
    return function (operator, a, b)
    {
        switch (operator) {
            case "add": {
                return addOp(a, b);
                break;
            }
            default: {
                return "?";
            }
        }
    }
});


app.js
require(["calc"], function (calc) {
    console.log(calc("add", 1, 2));
});


From my Node.js command prompt I tested the application:
>node \code\requirejs\r.js\dist\r.js app.js

Then built the application:
>node \code\requirejs\r.js\dist\r.js -o name=app out=go.js baseUrl=.

Then tested the build:
>node \code\requirejs\r.js\dist\r.js go.js

The build file (go.js) was concatenated and compressed as expected.  I ran it though a beautifier:


define("addop", [], function () {
    return function (e, t) {
        return e + t
    }
}), define("calc", ["addop"], function (e) {
    return function (t, n, r) {
        switch (t) {
            case "add":
                return e(n, r);
            default:
                return "?"
        }
    }
}), require(["calc"], function (e) {
    console.log(e("add", 1, 2))
}), define("app", function () {})