import/export modules

🧩 1. What Are Modules?

Modules allow you to split code into separate files and reuse functionality.

  • Each file is a module.
  • Modules can export values (variables, functions, classes) and import them in other files.

Benefits:

  • Better code organization
  • Avoid global scope pollution
  • Reusable and maintainable code

🟢 2. Exporting

🔹 Named Exports

You can export multiple things from a module by name.

// utils.ts
export const PI = 3.14;

export function add(a: number, b: number): number {
  return a + b;
}

export class Calculator {
  multiply(a: number, b: number) {
    return a * b;
  }
}
  • Each export must be imported with the same name.

🔹 Default Export

A module can have one default export, usually the “main thing” from that module.

// math.ts
export default function subtract(a: number, b: number) {
  return a - b;
}

🟡 3. Importing

🔹 Named Imports

import { PI, add, Calculator } from "./utils";

console.log(PI);         // 3.14
console.log(add(2, 3)); // 5

const calc = new Calculator();
console.log(calc.multiply(3, 4)); // 12
  • Must match the exported names.

🔹 Default Import

import subtract from "./math";

console.log(subtract(10, 4)); // 6

🔹 Renaming Imports

import { add as sum } from "./utils";

console.log(sum(5, 5)); // 10

🔹 Import Everything as an Object

import * as Utils from "./utils";

console.log(Utils.PI);          // 3.14
console.log(Utils.add(2, 3));  // 5

🔵 4. Combining Default and Named Exports

// module.ts
export const name = "Alice";
export default function greet() {
  console.log("Hello!");
}

// main.ts
import greet, { name } from "./module";

greet(); // Hello!
console.log(name); // Alice

🟣 5. TypeScript-Specific Notes

  • TypeScript supports type-only exports:
// types.ts
export type User = { id: number; name: string };
// main.ts
import type { User } from "./types";

const u: User = { id: 1, name: "Alice" };
  • import type ensures types are removed from compiled JS, reducing bundle size.

🟤 6. Relative vs Absolute Paths

  • Relative path: ./utils (current folder), ../utils (parent folder)
  • Absolute path: Can configure tsconfig.json baseUrl or paths
// tsconfig.json
{
  "compilerOptions": {
    "baseUrl": "./src",
    "paths": {
      "@utils/*": ["utils/*"]
    }
  }
}
import { add } from "@utils/helpers";

7. Best Practices

  1. Prefer named exports for reusable utilities.
  2. Use default exports for “main” functionality per file.
  3. Keep related exports together in one module.
  4. Use type-only exports in TypeScript for better tree-shaking.
  5. Use clear folder structure:
src/
 ├─ utils/
 │   ├─ math.ts
 │   └─ string.ts
 └─ components/
     └─ Button.tsx

🔹 Quick Example

// mathUtils.ts
export const add = (a: number, b: number) => a + b;
export const subtract = (a: number, b: number) => a - b;

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

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

Leave a Reply