Friday, December 12, 2014

RequireJS and TypeScript

Here is an example of a RequireJS module:
1
define([], function() {
2
    function Calculator() {
3
    }
4
 
5
    Calculator.prototype.calculate = function (x, y) {
6
        return x + y;
7
    };
8
 
9
    return Calculator;
10
});
To make sure this is compiling through the TypeScript compiler, the first step is to convert it to use modules from TypeScript. The simplest way is:
1
function Calculator() {
2
}
3
 
4
Calculator.prototype.calculate = function (x, y) {
5
  return x + y;
6
};
7
 
8
export = Calculator;
To compile this, you then call the compiler with the right module flag, which is AMD for RequireJS:
1
tsc Calculator.ts --module amd
This will then generate the equivalent JavaScript. You'll notice it adds some extra code that's probably unneccesary, but hey, I'll take that for compile time safety:
1
define(["require", "exports"], function(require, exports) {
2
    function Calculator() {
3
    }
4
 
5
    Calculator.prototype.calculate = function (x, y) {
6
        return x + y;
7
    };
8
 
9
    return Calculator;
10
});
If you're working in Visual Studio, you might get an error about it not using the module flag. If you're working with an existing codebase, you might find you'll need to add TypeScript support first - adding a new TypeScript file in VS2013 does this by adding some stuff to the CSPROJ file, namely the XML element TypeScriptToolsVersion, and will need to reload the project. Afterwards, there should be a new tab for TypeScript Build options in the project properties dialog where you can choose the module style:
404 - Image Not Found

No comments:

Post a Comment