I've started work on a large-scale typescript project.
Right from the outset, I want to keep my files organized (this project will be split between lots of developers so order is very necessary).
I have been attempting to use modules / namespaces and splitting classes out into separate files for each one, with a folder holding the namespace.
The file structure is:
app.ts \Classes ---- \Animals ---- ---- Mammals.ts ---- ---- Reptiles.ts
I then attempt to import all files in that namespace in app.ts using something like: import * as Animals from "./Classes/Animals"
As for the namespace files themselves, I have tried the following, with no success:
namespace Animals { export class Mammals { constructor() { } } }
and also:
module Animals { export class Reptiles { constructor() { } } }
Unfortunately, the path is never recognized (as it points to a folder and not a single file). Is this even possible? Having all my classes from a single namespace in one file will result in files which are thousands of lines long and for this project that is not maintainable.
I have also noticed that TypeScript 1.5 has support for tsconfig.json - however, having to add each file manually to the map is a sure-fire way of introducing issues when developers start adding classes.
NOTE: I'm using Visual Studio 2015, TypeScript 1.5 (I believe, not sure how to verify). I also have ES6 support turned on.
A module is a way which is used to organize the code in separate files and can execute in their local scope, not in the global scope. A namespace is a way which is used for logical grouping of functionalities with local scoping.
Don't use Custom TypeScript Modules and Namespaces Since we have ES6 modules as a standard in JavaScript, we don't need custom TypeScript modules and namespaces to organize our code. Instead, we should use standard JavaScript modules with import and export instead.
Use import myFunction from "./myModule" to bring it in. More commonly, TypeScript modules say export myFunction in which case myFunction will be one of the properties on the exported object. Use import { myFunction } from "./myModule" to bring it in.
By default, files in TypeScript are treated as global scripts. This means that any variable, class, function, or other construct declared in the file is available globally. As soon as you start using modules in a file, this file becomes module-scoped, and is no longer executed globally.
Use re-exporting to create an external module that groups and exposes types from other modules:
// Classes/Animals.ts export * from '.\Animals\Mammals'; export * from '.\Animals\Reptiles';
Then import the types from the new module as usual:
// app.ts import * as Animals from '.\Classes\Animals' let dog: Animals.Dog; let snake: Animals.Snake;
Or
// app.ts import { Dog, Snake } from '.\Classes\Animals' let dog: Dog; let snake: Snake;
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