I am getting lot of confusion with module/namespace/export and import, require, reference usage.
Being from Java background, Can someone explain me
In the early days of Typescript, the namespaces were called internal modules and the ES6 Modules were called external modules.
Now for declaring the namespaces, the Typescript team recommends using the namespace { } instead of the module { } syntax to avoid the naming confusion with the external modules. Because the external modules are now simply 'modules' and internal modules are 'namespaces'.
Declaration
A namespace in Typescript can be declared using either the namespace or the module keyword. Both the keywords do the same thing. Then we can decide which part of our namespace 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, the namespaces 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 ES6 modules to achieve this.
The namespaces are now used for ambient namespace declarations.
Single File Usage
We can declare namespaces across multiple files and they can be concatenated using --outFile flag. We can then use that concatenated file inside the 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.
Declaration
Modules are also called ES6 modules. We use multiple files for grouping the 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 in modules is achieved by using separate files for grouping the related functionalities. For this reason, the external modules are also called file modules.
Single File Usage
We don't load the modules of the client-side web application using the 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 modules are strongly recommended.
That's it!