TypeScript Modules

What Are Modules

In TypeScript (and modern JavaScript), modules are files that contain code with their own local scope. They help in organizing applications into small, self-contained, and reusable pieces of functionality. Each file that contains an export or importstatement is treated as a module.

By using modules, you can:

  • Split large applications into smaller, more manageable files.
  • Reuse code across multiple parts of your application or even in other projects.
  • Avoid global namespace pollution by keeping variables and functions scoped to the module.
  • Clearly define which parts of the code are accessible externally (via exports) and which remain private.

Each module can:

  • Export variables, functions, classes, interfaces, or type aliases.
  • Import and use code exported by other modules.

TypeScript modules follow the ECMAScript module standard (ESM) and useimport/export syntax by default, but they can also work withCommonJS modules for Node.js environments.

Exporting From a Module

Use the export keyword to make variables or functions accessible to other modules:

// mathUtils.ts - A module exporting a function
export function add(a: number, b: number): number {
  return a + b;
}

Importing Into Another File

Use the import keyword to bring in exports from other files:

// main.ts - Importing from mathUtils
import { add } from './mathUtils';

console.log(add(5, 3)); // Output: 8

You can also use aliases:

import * as MathUtils from './mathUtils';

Default Exports

A module can have a single default export:

// logger.ts
export default function log(message: string) {
  console.log("LOG:", message);
}

Imported without curly braces:

import log from './logger';

Module Resolution

TypeScript uses a strategy (usually "Node") to resolve file paths. This is controlled by settings like baseUrl and paths in tsconfig.json. Example:

{
  "compilerOptions": {
    "baseUrl": "./src",
    "paths": {
      "@utils/*": ["utilities/*"]
    }
  }
}

Best Practices

  • Use named exports for flexibility and clarity
  • Default export when a module exports only one main feature
  • Group related functionality in one module
  • Avoid circular dependencies by organizing modules cleanly

Need Help?

Ask the AI if you need help understanding or want to dive deeper in any topic