Johannes Klauß
Johannes Klauß

Reputation: 11040

Develop/Organize a node module in TypeScript

I want to develop a node module in TypeScript, but I'm having some problems with all the possible options to require, import, etc.

What I'm doing right now is having every class and interface in it's own file. So I would need to require all the dependencies which is kind of stupid, because I'm typing the class name twice, like this:

import Target = require('./Target');

export interface IFace {

    getTarget(): Target.Target
}

I could write import t = require('./Target'); instead but then I need to write t.Target which I think is also pretty ugly.

And also I can't give it a module name (like FaceApp), because when I need to import two files, there's a naming conflict.

Obviously that would not be needed if everything would live in one file, but this is far from optimal I think.

So how do you guys organize your node module in TypeScript? I'd be happy to hear your suggestions.

Upvotes: 0

Views: 166

Answers (2)

Troy Weber
Troy Weber

Reputation: 1075

The way recommended by TypeScript is to do

export default class Target {}

and then you can do a true typescript import with

import Target from './Target'

alternatively, you can rename it

import NewName from './Target'

Also note that you can export multiple things from a file if they are related

export class SomeClass {}
export class OtherClass {}

And that on import, you can change the names

import { SomeClass as MySomeClass, OtherClass as MyOtherClass } from './Target'

Upvotes: 0

basarat
basarat

Reputation: 276303

You can avoid the name duplication by using the export = syntax. i.e. Do:

class Target{}
export = Target;

instead of export class Target.

Also grunt-ts transformers can help you with the import statement explosion : https://github.com/grunt-ts/grunt-ts/issues/85#issue-29515541

Upvotes: 1

Related Questions