module.exports in typescript

Solution 1:

You can export a single class in TypeScript like this:

class Person {

  private firstName: string;
  private lastName: string;

  constructor(firstName: string, lastName: string) {
    this.firstName = firstName;
    this.lastName = lastName;
  }

  public getFullName() {
    return `${this.firstName} ${this.lastName}`;
  }
}

export = Person;

And here is how it's going to be used:

var Person = require('./dist/commonjs/Person.js');

var homer = new Person('Homer', 'Simpson');
var name = homer.getFullName();

console.log(name); // Homer Simpson

To be complete, here is my tsconfig.json (I am using TypeScript v2.0.3):

{
  "compilerOptions": {
    "module": "commonjs",
    "moduleResolution": "node",
    "outDir": "dist/commonjs",
    "rootDir": "src/ts",
    "target": "es5"
  },
  "exclude": [
    "dist",
    "node_modules"
  ]
}

Solution 2:

This has now been implemented and is ready in TypeScript 0.9 :)

Solution 3:

So I think I've found a workaround. Just wrap the keyword 'module' in parentheses in your .ts file:

declare var module: any;
(module).exports = MyClass;

The generated javascript file will be exactly the same:

(module).exports = MyClass;

Note, better than declaring var module yourself, download the node.d.ts definition file and stick it in the same directory as your typescript file. Here is a complete sample of an express node.js routing file which assumes node.d.ts is in same directory:

/// <reference path="node.d.ts" />
var SheetController = function () {
    this.view = function (req, res) {
        res.render('view-sheet');
    };
};
(module).exports = SheetController;

I can then new up a SheetController and (using express) assign the view method:

var sheetController = new SheetController();
app.get('/sheet/view', sheetController.view);

I suppose any keyword can be escaped using this pattern:

declare var reservedkeyword: any;
(reservedkeyword).anything = something;

Solution 4:

It's ugly and hacky, but you can still do:

class Greeter {}
declare var exports:any;
exports = Greeter;

Which compiles into:

var Greeter = (function () {
    function Greeter() { }
    return Greeter;
})();
exports = Greeter;