Introduction to Modules

Learn how to organize your code into modules using import and export statements. We'll cover both CommonJS and ES module syntax.


Introduction to TypeScript Modules

This guide provides a beginner-friendly introduction to modules in TypeScript. Modules allow you to organize your code into reusable and manageable units, making your projects more scalable and maintainable.

What are Modules?

In essence, a module is a self-contained block of code, typically encapsulating related functions, classes, variables, and interfaces. Think of them as logical building blocks for larger applications. Instead of having all your code in one massive file, you break it down into smaller, more manageable files, each representing a specific module.

Why use modules?

  • Code Organization: Improve code structure and readability.
  • Reusability: Share code across different parts of your application or even in different projects.
  • Maintainability: Make it easier to understand, modify, and debug your code.
  • Namespace Management: Avoid naming conflicts by creating separate scopes for your code.

Import and Export Statements

The key to using modules is understanding the import and export statements. export allows you to make code available to other modules, while import allows you to use code from other modules in your current file.

TypeScript supports two main module systems:

  1. CommonJS (CJS): Primarily used in Node.js environments.
  2. ES Modules (ESM): The standard module system for modern JavaScript and TypeScript.

CommonJS (CJS) Syntax

CommonJS uses require() for importing and module.exports for exporting.

Exporting in CommonJS

// math.ts (or math.js if you're running the compiled JavaScript in a Node.js environment)
function add(a: number, b: number): number {
  return a + b;
}

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

module.exports = {
  add: add,
  subtract: subtract
}; 

Importing in CommonJS

// app.ts (or app.js)
const math = require('./math');

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

ES Modules (ESM) Syntax

ES Modules use import and export keywords.

Exporting in ES Modules

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

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

// Alternatively, you can export multiple things at once:
// export { add, subtract }; 

Importing in ES Modules

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

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

Default Exports: You can also export a single default value from a module using the export default keyword. This is often used for exporting a main class or function.

// greeting.ts
export default function greet(name: string): string {
  return `Hello, ${name}!`;
} 
// app.ts
import greet from './greeting';  // No curly braces needed for default imports

console.log(greet('Alice')); // Output: Hello, Alice! 

Choosing between CommonJS and ES Modules

While CommonJS has been widely used in the past, ES Modules are now the preferred standard, especially for front-end development and newer Node.js projects. ES Modules offer several advantages, including better static analysis, tree shaking (removing unused code), and improved support in modern browsers.

When starting a new TypeScript project, it's generally recommended to use ES Modules.

Configuring TypeScript for ES Modules

To use ES Modules in TypeScript, you need to configure your tsconfig.json file. Make sure the module option is set to "esnext", "es2020", "es2022", or a similar ES version. You might also need to set the moduleResolution option to "node" or "node16" or "nodenext" for Node.js environments.

// tsconfig.json
{
  "compilerOptions": {
    "target": "es6",
    "module": "esnext",
    "moduleResolution": "node",
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "skipLibCheck": true
  }
} 

The esModuleInterop option allows you to import CommonJS modules as if they were ES modules. Setting it to true is often necessary for compatibility with existing libraries.

Summary

Modules are a powerful tool for organizing and structuring your TypeScript code. By using import and export statements, you can create reusable, maintainable, and scalable applications. Experiment with both CommonJS and ES Modules to understand their differences and choose the best approach for your project.