Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is it not possible to export a class instance in TypeScript?

I didn't find a way to export a class instance easily in TypeScript. I had to come up with the following workaround to generate proper javascript code.

 var expo = new Logger("default");
 export = expo;

generates

var expo = new Logger("default");
module.exports = expo;

Is there an easier way of achieving this?

like image 879
Christopher Klewes Avatar asked Apr 08 '15 20:04

Christopher Klewes


People also ask

How do I export a class instance 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 can you 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.

Does ts not have default export?

The "Module has no default export" error occurs when we try to import as default from a module that doesn't have a default export. To solve the error make sure the module has a named export and wrap the import in curly braces, e.g. import {myFunction} from './myModule' .


1 Answers

Quite by accident, I found this way to export an instance:

class MyClass(){}

export default new MyClass();
like image 159
Greg Gum Avatar answered Oct 21 '22 03:10

Greg Gum