How internal is different from external modules?


TypeScript, an extension of JavaScript, introduces modules as a means to structure and organize code effectively. Modules play a vital role in developing scalable and maintainable applications by enabling code encapsulation and reusability. TypeScript supports two types of modules: internal (namespaces) and external (ES modules).

In this article, we will delve into the differences between internal and external modules in TypeScript, exploring their characteristics and impact on code organization and sharing within a project.

Internal Modules

Internal modules, also known as namespaces, serve as logical containers within a single file to group related code elements together. They offer benefits such as preventing naming conflicts and providing improved organization and encapsulation. Internal modules are defined using the namespace keyword in TypeScript.

An example of an internal module in TypeScript could be a file named math.ts, containing mathematical operations −

namespace Math {
   export function add(a: number, b: number): number {
      return a + b;
   }
   export function subtract(a: number, b: number): number {
      return a - b;
   }
}

By organizing related functions within the Math namespace, we can prevent naming collisions and enhance code maintainability. Internal modules can also be split across multiple files using the /// <reference path="..." /> syntax, allowing developers to organize code based on functionality.

However, internal modules have limitations. They lack the same level of modularity as external modules since their scope is limited to the enclosing file or module. As a project grows, managing internal modules can become challenging, potentially resulting in code duplication or tight coupling.

External Modules

External modules, also known as ES modules, enable code encapsulation within individual files and facilitate code sharing across different files and projects. They adhere to widely adopted module syntax such as CommonJS or ES6, allowing interoperability with various module systems and bundlers.

An example of an external module in TypeScript could be a file named calculator.ts, exporting mathematical operations −

export function add(a: number, b: number): number {
   return a + b;
}

export function subtract(a: number, b: number): number {
   return a - b;
}

Here, the functions add and subtract are exported, making them accessible to other files or modules. External modules promote a modular and decoupled architecture, where components can be developed independently and composed together as needed. This facilitates code reuse and supports the creation of libraries and reusable modules that can be easily shared and consumed.

External modules have gained significant popularity with modern JavaScript and tooling support. TypeScript itself encourages the use of external modules as the recommended approach for building scalable and maintainable applications.

Example 1: Internal Modules

Setup the TypeScript project using −

$ npm i -g typescript
$ tsc --init

In this example, we have an internal module called MathUtils. It contains two functions: add and subtract, which perform addition and subtraction operations on numbers.

MathUtils.ts

export namespace MathUtils {
   export function add(a: number, b: number): number {
      return a + b;
   }

   export function subtract(a: number, b: number): number {
      return a - b;
   }
}

In the main.ts file, we use the import statement to import the MathUtils namespace from the mathUtils.ts file.

import { MathUtils } from './mathUtils';
const result1 = MathUtils.add(5, 3);
console.log(`Result of addition: ${result1}`);
const result2 = MathUtils.subtract(10, 4);
console.log(`Result of subtraction: ${result2}`);

We then use the functions add and subtract from the MathUtils namespace to perform addition and subtraction operations, respectively. The results are stored in result1 and result2 variables, and their values are displayed using console.log().

To compile we run following commands −

$ tsc main.ts
$ node main.js

Output

It will produce the following outout −

Result of addition: 8
Result of subtraction: 6

By using an internal module, we can encapsulate these related functionalities within the Catalog namespace, preventing naming conflicts with other parts of the codebase.

Example 2: External Modules

We will use the same process as in Example 1 to setup a new TypeScript project again.

Now, let's consider an external module example where we have two separate files: calculator.ts and app.ts. The calculator.ts file exports mathematical operations, and the app.ts file imports and uses those operations.

calculator.ts

export function add(a: number, b: number): number {
   return a + b;
}

export function subtract(a: number, b: number): number {
   return a - b;
}

app.ts

import { add, subtract } from "./calculator";
console.log(`The sum of 3 and 5 is: ${add(5, 3)}`); // Output: 8
console.log(`The difference between 4 and 10 is: ${subtract(10, 4)}`); // Output: 6

In this example, the calculator.ts file exports the add and subtract functions using the export keyword. These functions can then be imported and used in the app.ts file by specifying the relative path ('./calculator'). The imported functions can be called directly, providing modularity and code reuse.

Output

It will produce tehe following output −

The sum of 3 and 5 is: 8
The difference between 4 and 10 is: 6

Conclusion

In conclusion, understanding the difference between internal and external modules in TypeScript is crucial for organizing code effectively. Internal modules offer better organization and prevent naming conflicts within a file or module. However, they can become unwieldy in larger projects. External modules provide a more modular and shareable approach, enhancing reusability and collaboration. For most projects, external modules are the preferred choice as they offer flexibility and scalability. By leveraging modules, TypeScript developers can improve code organization, promote reusability, and build robust applications.

Updated on: 01-Aug-2023

137 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements