13

I'm familiar with the export keyword in TypeScript, and two canonical ways of exporting things from Node modules using TypeScript (of course, the TypeScript modules can be used as well, but they are even further from what I'm looking for):

export class ClassName { }

and a series of

export function functionName () { }

However, the way I usually write my modules, so that they are later imported as instantiable closures, is:

var ClassName = function () { };
ClassName.prototype.functionName = function () { };
module.exports = ClassName;

Is there a way I can do this using the TypeScript export syntax?

2 Answers 2

23

You can do that quite simply in TypeScript 0.9.0 :

class ClassName { 
    functionName () { }
}

export = ClassName;
Sign up to request clarification or add additional context in comments.

3 Comments

Remove the export from the class definition and it works perfectly. Thanks :)
@BraedenP yeah sorry, forgot that :)
Damn, why I'm so stupid. I was using AMD modules with node for a while :facepalm:
3

Here is how I export CommonJS (Node.js) modules with TypeScript:

src/ts/user/User.ts

export default class User {
  constructor(private name: string = 'John Doe',
              private age: number = 99) {
  }
}

src/ts/index.ts

import User from "./user/User";

export = {
  user: {
    User: User,
  }
}

tsconfig.json

{
  "compilerOptions": {
    "declaration": true,
    "lib": ["ES6"],
    "module": "CommonJS",
    "moduleResolution": "node",
    "noEmitOnError": true,
    "noImplicitAny": true,
    "noImplicitReturns": true,
    "outDir": "dist/commonjs",
    "removeComments": true,
    "rootDir": "src/ts",
    "sourceMap": true,
    "target": "ES6"
  },
  "exclude": [
    "bower_components",
    "dist/commonjs",
    "node_modules"
  ]
}

dist/commonjs/index.js (Compiled module entry point)

"use strict";
const User_1 = require("./user/User");
module.exports = {
    user: {
        User: User_1.default,
    }
};
//# sourceMappingURL=index.js.map

dist/commonjs/user/User.js (Compiled User class)

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
class User {
    constructor(name = 'John Doe', age = 72) {
        this.name = name;
        this.age = age;
    }
}
exports.default = User;
//# sourceMappingURL=User.js.map

Testing code (test.js)

const MyModule = require('./dist/commonjs/index');
const homer = new MyModule.user.User('Homer Simpson', 61);
console.log(`${homer.name} is ${homer.age} years old.`); // "Homer Simpson is 61 years old."

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.