Open In App

What are the Modules in Typescript ?

In this article, we talk about what types of modules are introduced by TypeScript. Before we discuss the types of modules we will see what the module concept is. Let’s see.

When ES6 introduced the concept of the module, JavaScript started supporting the module concepts as a part of the JavaScript library. When TypeScript comes into the picture it also shares the module with JavaScript. The TypeScript module allows it to contain both the declaration and its code. The module executes in local environments, not in the global scope. That means when we define the functions, variables, classes, interfaces, etc., in the module, it cannot be visible outside the module until you cannot export the module using the export statement. If you want to access the variables, and functions in the module, you must import the module into your file by using the import statement.



Types of modules in TypeScript: A module is designed to write organized code. TypeScript modules are divided into two parts:

1. Internal Module: Internal module is used to logically group variables, functions, classes, and interfaces in one unit and then export it in the other module. TypeScript gives the name of this logical grouping as a namespace in the latest version. In the old module concept namespace is not present, instead namespace we use the traditional way to use modules in old versions.



Syntax:

import { sample_file } from “./sample_file”;

Example 1: We will write a message that displays and export the message using export default. 




const message = () => {
    const name = "Jesse";
    const age = 40;
    return name + ' is ' + age + 'years old.';
};
export default message;




<!DOCTYPE html>
<html>
 
<body>
    <h1 style="color:green">Hello GFG</h1>
    <h1>JavaScript Modules</h1>
    <p id="demo"></p>
    <script type="module">
        import message from "./message.js";
        document.getElementById("demo").innerHTML = message();
    </script>
</body>
 
</html>

Output:

Internal module 

2. External Module: External modules in TypeScript are used to specify and load dependencies between multiple external js files. If there is only one js file used, then in this case external modules are not used. In that case we use traditional dependency management between JavaScript files by using browser script tags (<script></script>).

But that’s not always possible, as it’s very linear while loading modules. That means instead of loading files one after another there is no asynchronous option to load modules. When you are programming js for the server for example NodeJs you don’t even have script tags.

Syntax:

export interface sample_file {
    ...
}

There are two alternative ways for loading dependent JS files from a single JavaScript file. They are:

  1. Client Side: RequireJs
  2. Server Side: NodeJs

Selecting a Module Loader: To support loading external JavaScript files in the module, we will use a module loader. This will be done by using another js library RequireJs. RequireJS is the most popular library used for browsers. 
This is implemented by AMD (Asynchronous Module Definition) specification. Instead of loading files one by one, AMD allows loading them all separately, even if they are dependent on each other.

Defining External Module: When defining an external module in TypeScript use CommonJS or AMD, and consider each file as a module. So it’s optional to use the internal module within the external module.
If you are migrating TypeScript from AMD to CommonJs module systems, then there is no additional work needed. The only thing you need to change is just the compiler flag. Unlike in JavaScript, there is an overhead in migrating from CommonJs to AMD or vice versa.

Example 1: This example will illustrate the use of an external module with single files:




export function multiple(x: number, y: number): number {
    log(`${x} * ${y}`);
    return x + y;
}
function log(message: string): void {
    console.log("Numbers", message);
}




import { multiple } from "./script";
console.log('Value of x*y is:', multiple(6, 2));

Steps to run the application: First, convert the TypeScript file into JavaScript for that you need to run the following command on your respective terminal.

tsc Script.ts

After that, you need to run a JavaScript file using the Node module. as shown below.

node Index.js

Output:

External module 

Example 2: This example will illustrate the use of an external module with  multiple files:




export class Student {
    stuCode: number;
    stuName: string;
    constructor(name: string, code: number) {
        this.stuName = name;
        this.stuCode = code;
    }
    displayStudent() {
        console.log("Student Code: " + this.stuCode
            + ", Student Name: " + this.stuName);
    }
}




import { Student } from "./Student";
let empObj = new Student("Jhon", 100);
empObj.displayStudent();

Steps to run the application: First, convert the TypeScript file into JavaScript for that you need to run the following command on your respective terminal.

tsc StudentDetails.ts

After that, you need to run a JavaScript file using the Node module. as shown below.

node StudentDetails.js

Output:

External Module 


Article Tags :