Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

module.exports in typescript

does somebody know how to do a module.exports?

I tried some different ways ending up with

export class Greeter {} 

which will compile to

exports.Greeter = Greeter; 

But what I really want is this:

exports = Greeter; 

So that I can use it like this:

import { Greeter } from "greeter";  const greeter = new Greeter(); 

and not

import { Greeter } from "greeter";  const greeter = new Greeter.Greeter(); 

Is this possible with Typescript?

like image 251
Kersten Avatar asked Oct 02 '12 18:10

Kersten


People also ask

What is a module in TypeScript?

In TypeScript, a module is a file containing values, functions, or classes. You can make some of them public, i.e. visible from other modules, by exporting them. Non exported objects are private. Let's create a very simple math module with a single exported function!

How do I export an object in TypeScript?

TypeScript has export = syntax. It specifies a single object that is exported from the module. This can be a function, class, interface, namespace, or enum.

How do you export functions in TypeScript?

Use named exports to export a function in TypeScript, e.g. export function sum() {} . The exported function can be imported by using a named import as import {sum} from './another-file' . You can use as many named exports as necessary in a single file.


1 Answers

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"   ] } 
like image 187
Benny Neugebauer Avatar answered Sep 22 '22 09:09

Benny Neugebauer