Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Export class as Node.js module in TypeScript

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?

like image 478
BraedenP Avatar asked Jul 06 '13 02:07

BraedenP


People also ask

How do I export a class object in TypeScript?

Use named exports to export multiple classes in TypeScript, e.g. export class A {} and export class B {} . The exported classes can be imported by using a named import as import {A, B} from './another-file' . You can have as many named exports as necessary in a file.

What is export {} in TypeScript?

TypeScript supports export = to model the traditional CommonJS and AMD workflow. The export = syntax specifies a single object that is exported from the module. This can be a class, interface, namespace, function, or enum.

How do I use ES module in TypeScript?

To use TypeScript with ES Modules, the TypeScript compiler configuration in tsconfig. json can be updated to process code in ES Module format. Additionally, Babel can be used for TypeScript compilation, and the TypeScript compiler will be used for type checking, as Babel can not type check TypeScript code.

How can we access a class of module from outside in TypeScript?

In typescript by using an import statement, a module can be utilized in another module. any variables, classes, methods, or other objects declared in a module are not accessible outside of it. The keyword “export” may be used to construct a module, and the term “import” can be used to import it into another module.


1 Answers

You can do that quite simply in TypeScript 0.9.0 :

class ClassName { 
    functionName () { }
}

export = ClassName;
like image 98
basarat Avatar answered Oct 16 '22 08:10

basarat