It seems that the information on how to actually structure code when writing Typescript is next to non-existent.
I want to make a server in node. It has external dep
For anyone who stumbles across this thread (like me) who are trying to create one barrel file for external module declarations, loretoparisi's answer is the way to go. Here is my use case with example modules. I wanted to have a barrel declaration file (index.d.ts
) for all my 3rd party declarations I was writing, but didn't want to put it 6 + module declarations in the same file. So this is what I did.
I have a folder structure like this:
src/
index.ts
Example index.ts
:
import WildEmitter from 'wildemitter';
import SomethingCool from 'somethingcool';
// ... rest of file
I converted my folder structure like this to write declaration files for my imported 3rd party modules:
src/
index.ts
/types
index.d.ts
/modules
wildemitter.d.ts
somethingcool.d.ts
In my src/types/index.d.ts
file, I have:
/// <reference path="modules/wildemitter.d.ts" />
/// <reference path="modules/somethingcool.d.ts" />
Then I can keep my module declarations in separate files.
In src/types/modules/wildemitter.d.ts
I have:
declare module 'wildemitter' {
// declarations
}
Hopefully this helps someone!
Actually you can (by now):
file: class1.ts:
export class Class1 {
name: string;
constructor(name: string){
this.name = name;
}
}
file: class2.ts:
export class Class2 {
name: string;
}
consolidating module file: classes.ts:
export { Class1 } from "./class1";
export { Class2 } from "./class2";
consuming file:
import { Class1, Class2 } from "./classes";
let c1 = new Class1("Herbert");
let c2 = new Class2();
In this manner you can have one class (or interface) per file. In one consolidating module file (classes.ts) you then reference all entities that make up your "module".
Now you only have to reference (import) on single module file to access all of your classes. You still have a neat compartmentalization between files.
Hope this helps anyone still looking.
Multi-file external modules are not supported yet in TypeScript.
For module structuring recommendations, this page has a good rundown of the options. In particular, if you have exactly one class per file, you can use export =
so that the second line of code in your example would simply be var vec = new vector();
, which would be reasonably straightforward.