Kim Gysen Kim Gysen - 1 year ago 83
Javascript Question

Typescript default export

I just started taking a look at Typescript and have an issue when playing around.

I want to write a library to manage a general tree structure and just doing some very basic tests to see how TS works.

Start of the simple setup with 3 files:

  • GForest.ts

  • GTree.ts

  • GNode.ts

Currently, GForest.ts:

import * as Immutable from "immutable";
import GTree from "./GTree";

export default class Forest{
public static createTree(){
let tree = new GTree();


export default class GTree{
console.log("Tree constructed");

public static createNode(){


I created a simple test.js file to call the library (compiled TS to ES5):

var GForest = require("./build/GForest");


When running

> node test

The output is:

I don't understand why the result is:

{ default: { [Function: Forest] createTree: [Function] } }

Why is there an object with
as key and how do I change this to achieve desired behaviour?

Because of this, I'm unable to just call:


(I want to expose the creation of a tree through a static factory)
Any help?

Answer Source

Use the ES6 default export

I quote the article ES6 In Depth: Modules from Mozilla:

If you’d like your own ES6 module to have a default export, that’s easy to do. There’s nothing magic about a default export; it’s just like any other export, except it’s named "default".

In your test.js file, the "default" feature is inelegant because you want to consume the ES6 default export from an ES5 syntax. I suggest to use TypeScript:

// test.ts
import GForest from "./build/GForest";
console.log(GForest); // { [Function: Forest] createTree: [Function] }

This code is compiled to:

var GForest_1 = require("./build/GForest"); 

Directly export a class

In TypeScript, you can directly export a member with the syntax export =.


// GForest.ts
import * as Immutable   from "immutable"; 
import GTree            from "./GTree"; 

class Forest{ 
    public static createTree(){ 
        let tree = new GTree(); 
export = Forest;

Then, use it with a code ES3/5:

// test.js
var GForest = require("./build/GForest"); 
console.log(GForest); // { [Function: Forest] createTree: [Function] }

... or, in TypeScript:

// test.ts
import * as GForest from "./build/GForest";
console.log(GForest); // { [Function: Forest] createTree: [Function] }

See the documentation on export = here.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download