Introduction
A Typescript Module is a feature that allows the user to break the source code into multiple files. This code becomes easy to manage, decode and debug. Let us consider the process of baking a pizza.
We require sliced vegetables, seasonings, dough, cheese, and pizza sauce. If we did all the preparations in a single station, it would become quite messy and hard to manage. If we divided these steps into different stations, the process would become straightforward.
This is the principle behind modules. We separate the functions, classes, and declarations from the main file and use only the prepared pieces of code.
Modules use the export keyword to export a particular piece of code from a file and import to impart that piece of code into another.
Another benefit of Typescript Modules is that if an identical function or class is required in another file, we only need to import the function or the class name instead of copying the entire function or class to the target file.
Types of Modules
Modules can be classified into two types:
- Internal Module
- External Module
Internal Module
Internal Module is used to group functions, classes, interfaces, and variables into a single package. This package can be used locally, or its components can be exported using the export keyword into another module. This Module is known as a Namespace. Namespaces were the earlier versions of Modules and hence are obsolete.
//INTERNAL MODULE
//NAMESPACE
namespace Math {
function addition(a, b) {
console.log(a+b);
}
function subtraction(a, b) {
console.log(a-b); }
}
Math.addition(5,4);
Math.subtraction(9,7);
To export namespace, the export keyword is used before the function declaration.
//EXPORTING NAMESPACE
namespace Math {
export function addition(a, b) {
console.log(a+b);
}
export function subtraction(a, b) {
console.log(a-b); }
}
External Module
External Module is the latest version of Modules and has a straightforward approach to achieve cleaner code.
Instead of creating a package that consists of exportable functions, classes, or declarations, any class, function, or declaration can be exported from a file to another.