S
S
samizdam2016-04-02 15:26:23
Node.js
samizdam, 2016-04-02 15:26:23

What is the correct way to export/import TypeScript classes from npm package?

In my package written in TS, I use namespaces and put each class in a separate file. For example like this:

// src/MyProject/Foo.ts
namespace MyProject{
  export class Foo{}
}
// src/MyProject/Bar.ts
namespace MyProject{
  export class Bar{}
}

Then I collect this case into a single index.js using tsc and pack it into an npm package.
In another project, I am installing this package in node_modules and want to inherit its classes. For example like this:
namespace AnotherProject {
  export class Baz extends MyProject.Bar{}
}

There are so many syntaxes in node and TS for this - *.d.ts, require, export, import, module, namespace, ref - that I'm already confused... What is the correct syntax for exporting from a package and then importing in client code I should use?
PS: Typescript version 1.8.9, nodejs 5.4.1

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Super User, 2016-04-02
@sergeystepanov1988

Read about namespace here . The official documentation says that namespaces are not really needed when the code is modularized.
So just use export on modules and import on files that use those modules.

/* src/Animal.ts */
export default Animal {
    constructor(){}
}

/* src/Cat.ts */
import Animal from './Animal';
export default Cat extends Animal {
    constructor(){
        super();
    }
}

/* index.ts */
import  Cat from 'src/Cat';
let kitty = new Cat();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question