Start Coding

Topics

TypeScript Module Basics

TypeScript modules are a powerful feature for organizing and structuring code in larger applications. They provide a way to encapsulate related functionality and control visibility of variables, functions, and classes.

What are TypeScript Modules?

Modules in TypeScript are similar to JavaScript modules. They allow you to split your code into separate files, each containing a portion of your application's functionality. This separation promotes code reusability and maintainability.

Creating a Module

To create a module in TypeScript, simply write your code in a separate .ts file. Any declarations in this file are scoped to the module and not visible globally unless explicitly exported.

// math.ts
export function add(a: number, b: number): number {
    return a + b;
}

export const PI = 3.14159;

Exporting from a Module

Use the export keyword to make declarations available outside the module. You can export variables, functions, classes, and interfaces.

For more details on exporting, check out the guide on Export and Import in TypeScript.

Importing from a Module

To use functionality from another module, use the import statement. You can import specific items or the entire module.

// app.ts
import { add, PI } from './math';

console.log(add(2, 3));  // Outputs: 5
console.log(PI);         // Outputs: 3.14159

Module Resolution

TypeScript uses various strategies to resolve module imports:

  • Classic: Node.js-style resolution
  • Node: For compatibility with Node.js module resolution
  • Path mapping: Custom path aliases defined in tsconfig.json

The resolution strategy can be configured in your tsconfig.json file.

Best Practices

  • Use one module per file for clarity and maintainability
  • Name your module files descriptively
  • Prefer named exports over default exports for better tooling support
  • Use barrel files (index.ts) to simplify imports from complex module structures

Module Augmentation

TypeScript allows you to extend existing modules with new functionality. This is particularly useful when working with third-party libraries.

// augmentation.ts
import { MyModule } from 'some-library';

declare module 'some-library' {
    interface MyModule {
        newFunction(): void;
    }
}

MyModule.prototype.newFunction = function() {
    console.log('New functionality added!');
};

Understanding modules is crucial for building scalable TypeScript applications. They provide a foundation for organizing code and managing dependencies effectively.

For more advanced module concepts, explore Dynamic Imports and Ambient Modules in TypeScript.