Exporting and Importing in TypeScript Modules

In TypeScript, modules serve as a crucial mechanism for organizing and managing code. They enhance code reusability and maintainability while also improving readability and reliability.

TypeScript supports exporting module contents using the export keyword and importing contents from other modules using the import keyword. Within a module, you can define various types of variables, including classes, functions, constants, and type aliases.

TypeScript supports two module systems: CommonJS and ES6. CommonJS is the module system used by Node.js, while ES6 refers to the module system defined in the ECMAScript 6 standard. They feature distinct syntaxes and semantics.

In CommonJS, modules export their contents using module.exports and import other modules' contents using require(). For example:

// Define a module
// math.js
function add(a, b) {
  return a + b;
}
module.exports = {
  add: add
};

// Import the module
// main.js
const math = require('./math');
console.log(math.add(1, 2)); // Outputs 3

In ES6, modules export their contents using export and import other modules' contents using import. For example:

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

// Import the module
// main.ts
import { add } from './math';
console.log(add(1, 2)); // Outputs 3

Please note that when using ES6 modules, you must set the file extension to .mjs or configure "module": "esnext" in your tsconfig.json file.