Internal Modules: namespace
or module
keyword
Declaration
An Internal module can be declared using either the namespace
or the module
keyword. Then we can decide which part of our internal module to make public using the export
keyword.
// LivingThings.ts
export namespace Animals {
export class Dog { }
export class Cat { }
}
export namespace Plants {
export class Orchid { }
export class Bamboo { }
}
// LivingThingsUser.ts
import { Animals, Plants } from "./LivingThings"
Logical Grouping
Before ES6, internal modules were used in Typescript for encapsulating the interfaces, classes, functions and variables to support a group of related functionalities and hide implementation details. This way we could prevent variables from leaking into the global space. This helped in better code organisation and prevent name collisions. Now it is recommended to use external modules (ES6 modules) to achieve this.
The internal modules are now used for ambient namespace declarations.
Single File Usage
We can declare internal modules across multiple files and they can be concatenated using --outFile
flag. We can then use that concatenated file inside the <script>
tag in our HTML page. This allows us to structure our code in a good way in a client-side web application with all dependencies included.
External Modules: just export
and import
keywords
Declaration
External Modules are also called ES6 modules. We use multiple files for grouping related functionalities and just use the export
keyword to make the desired object publicly visible.
// Animals.ts
export class Dog { }
export class Cat { }
// Plants.ts
export class Orchid { }
export class Bamboo { }
// LivingThingsUser.ts
import { Dog, Cat } from "./Animals"
import { Orchid, Bamboo } from "./Plants"
Logical Grouping
The logical grouping is achieved by using separate files for grouping related functionalities. For this reason, the external modules are also called file modules.
Single File Usage
We don't load the external modules of the client-side web application using the <script>
tag, because the browsers may get sluggish while downloading so many files and rendering the page at the same time. For this, we use the module loaders like the CommonJS, AMD, SystemJS that enable us to load files asynchronously or concatenate the external module files into a single optimized file.
For server-side, especially in Node.js, the external modules are strongly recommended.
Nomenclature
For declaring the internal modules, the typescript team recommends using the namespace { }
instead of the module { }
syntax to avoid confusion with the external modules. Because the external modules are now simply 'modules' and internal modules are 'namespaces'.
That's it!