Understanding TypeScript Modules and Imports


Introduction

Modularization is a key concept in modern software development, and TypeScript provides a powerful way to structure your code into modules. Modules help organize and manage code by dividing it into smaller, reusable pieces. In this guide, we'll explore TypeScript modules, how to create and use them, and how to import and export functionality across modules.


What is a TypeScript Module?

A TypeScript module is a file that encapsulates related code, data, and functionality. Modules help you organize your code into smaller, manageable units, making it easier to maintain, test, and reuse. TypeScript provides support for both CommonJS and ES6-style modules.


Creating a Module

To create a module in TypeScript, you can use the export keyword to specify which parts of the module should be accessible from other modules.


Example (math.ts):

// Exporting variables and functions
export const pi = 3.14159265359;
export function add(a: number, b: number): number {
return a + b;
}

Importing from Modules

To use functionality from other modules, you can use the import statement. TypeScript supports both named imports and default imports.


Example (app.ts):

// Named import
import { pi, add } from "./math";
console.log("Value of PI:", pi);
console.log("Sum of 2 and 3:", add(2, 3));
// Default import (if math.ts has a default export)
import mathLibrary from "./math";
console.log("Value of PI:", mathLibrary.pi);
console.log("Sum of 2 and 3:", mathLibrary.add(2, 3));

Re-Exporting from Modules

You can also re-export functionality from one module to make it accessible from another module using the export...from syntax.


Example (index.ts):

// Re-exporting from math.ts
export { pi, add } from "./math";

Module Resolution

TypeScript uses module resolution to locate and load modules. It can resolve modules using different strategies, including Node.js-style resolution and path-based resolution.


Conclusion

TypeScript modules and imports are fundamental to structuring and organizing your code. They help you create reusable, maintainable, and modular software. By understanding how to create and import modules, you can better manage code dependencies and build complex applications with ease.