Import, Export, and Module Resolution - Textnotes

Import, Export, and Module Resolution


Learn how to organize TypeScript code using modules and namespaces. This module explains import/export syntax, module resolution, and best practices for structuring scalable applications.

1. Import and Export Syntax

Modules allow you to split code into separate files and reuse functionality across your project. TypeScript uses ES6 module syntax.

Exporting

You can export variables, functions, or classes from a module.


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

export const PI = 3.14;

export class Calculator {
multiply(a: number, b: number) {
return a * b;
}
}

Importing

You can import exported members in another file.


// app.ts
import { add, PI, Calculator } from "./mathUtils";

console.log(add(5, 10)); // 15
console.log(PI); // 3.14
const calc = new Calculator();
console.log(calc.multiply(2, 3)); // 6

Default Export


// greet.ts
export default function greet(name: string) {
console.log(`Hello, ${name}`);
}

// app.ts
import greet from "./greet";
greet("Muni"); // Hello, Muni

2. Module Resolution

Module resolution determines how TypeScript finds the files referenced in import statements.

Types of Module Resolution

  1. Classic
  2. The older strategy, used for legacy code.
  3. Searches relative paths without node_modules.
  4. Node
  5. Mimics Node.js resolution logic.
  6. Searches node_modules and supports extensions like .ts, .js, .json.
  7. Default in modern TypeScript projects.

Example


import { readFile } from "fs"; // Node module resolution finds this in node_modules
import { add } from "./mathUtils"; // Relative path

tsconfig.json Settings


{
"compilerOptions": {
"module": "commonjs",
"moduleResolution": "node",
"baseUrl": "./src",
"paths": {
"@utils/*": ["utils/*"]
}
}
}
  1. baseUrl and paths help resolve modules using aliases.
  2. Correct module resolution ensures smooth compilation and avoids "module not found" errors.

Conclusion

Modules and namespaces in TypeScript provide a structured approach to organizing code. Understanding import/export syntax and module resolution is essential for building maintainable, scalable applications with clean separation of concerns.