What is the pattern for one class per file where multiple classes (and therefore multiple files) contribute to the same namespace? I'm asking this specifically in a Node.js context.
I know how to define one class per file in the same namespace:
foo/A.ts:
module foo {
export class A {
}
}
foo/B.ts:
module foo {
export class B {
}
}
main.ts:
/// <reference path="./foo/A.ts"/>
/// <reference path="./foo/B.ts"/>
// TODO: How do I import the foo namespace at runtime?
TypeScript is supposedly a language for application-scale JavaScript development, yet we seem to be left out in the cold on the most fundamental aspect of application-scale development, which is how to layout and structure code files and how everything is linked together at runtime.
To use it, it must be included using triple slash reference syntax e.g. ///<reference path="path to namespace file" /> . Must import it first in order to use it elsewhere. Compile using the --outFile command. Compile using the --module command.
Typescript is a superset of ES6 so you have more power in what you can do, but that doesn't mean you should do it. In this case, ES6 solved the problem of modularization for us by doing a good job, so we don't need any namespace at all in common programs (unless you specifically want to use namespaces).
In TypeScript, files containing a top-level export or import are considered modules.
Specifies which commands are exported from a namespace. The exported commands are those that can be later imported into another namespace using a namespace import command. Both commands defined in a namespace and commands the namespace has previously imported can be exported by a namespace.
As basarat mentions, in Node.js, files are modules. The correct way to write the code you are working on is:
foo/A.ts:
class A {
}
export = A;
foo/B.ts:
class B {
}
export = B;
main.ts:
import A = require('./foo/A');
import B = require('./foo/B');
This is detailed in the Imports and Exports section of The Definitive Guide to TypeScript.
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