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?
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With