Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript module import in nodejs

Tags:

What is best practice for importing modules in nodejs with typescript? I come from c# background so I want to do something like this

MyClass.ts

module MyNamespace {     export class MyClass {     } } 

app.ts

// something like using MyNamespace new MyNamespace.MyClass(); 

or

MyClass.ts

export class MyClass { } 

app.ts

import MyClass = module("MyClass") new MyClass(); 

I know I can do this and it will work, but then I have to think up for two names for each class

import MyClass2 = module("MyClass") new MyClass2.MyClass(); 

Point is separating classes to multiple .ts files (preferably one file per class). So question is, how is this done?

like image 560
user1756840 Avatar asked Oct 18 '12 15:10

user1756840


People also ask

How do I import a custom module in TypeScript?

The export = syntax specifies a single object that is exported from the module. This can be a class, interface, namespace, function, or enum. When exporting a module using export = , TypeScript-specific import module = require("module") must be used to import the module.

Can I use TypeScript module in JavaScript?

The first is the TypeScript language — this is a new language which contains all JavaScript features . Check out the specs for more information. The second is the TypeScript compiler, tsc (the type system engine) which is a compilation engine that builds ts files and yields js files.


1 Answers

You have two choices here:

If you insist on using CommonJS or AMD modules, then you will have to use external modules just the way you described it in your question. Whether or not you use a module to declare your own namespace is mostly a matter of taste. The only way to circumvent the issue of specifying two names is to create a variable that aliases the type:

mymodule.ts

export module MyNamespace {     export class MyClass {     } } 

app.ts

import ns = require('mymodule'); var myclass = new ns.MyNamespace.MyClass(); var myclassalias = ns.MyNamespace.MyClass; var myclass2 = new myclassalias(); 

Your other option is to use internal modules which are mostly used to structure your code internally. Internal modules are brought into scope at compile time using reference paths.

mymodule.ts

module MyNamespace {     export class MyClass {     } } 

app.ts

///<reference path='mymodule.ts'/> var myclass = new MyNamespace.MyClass(); 

I think you'll have to decide for yourself which of those two approaches is more appropriate.

like image 115
Valentin Avatar answered Nov 28 '22 08:11

Valentin