📘

Modules and Imports/Exports

Beginner
80 XP
30 min
Lesson Content

Modules in TypeScript

Modules help organize code into reusable pieces. Essential for React components, Vue components, and Angular services.

Exporting

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

export const PI = 3.14;

// Default export
export default class Calculator {
  // ...
}

Importing

// Named imports
import { add, PI } from "./math";

// Default import
import Calculator from "./Calculator";

// Import all
import * as MathUtils from "./math";

Re-exporting

// Re-export from another module
export { add, subtract } from "./math";
Example Code

Practice with exports and imports

// In a real project, this would be in separate files
// For practice, we'll simulate modules

// Simulated export
const mathUtils = {
  add: (a: number, b: number) => a + b,
  multiply: (a: number, b: number) => a * b
};

// Simulated import
const { add, multiply } = mathUtils;

console.log(`Sum: ${add(5, 3)}`);
console.log(`Product: ${multiply(5, 3)}`);

Expected Output:

Sum: 8
Product: 15
Study Tips
  • Read the theory content thoroughly before practicing
  • Review the example code to understand key concepts
  • Proceed to the Practice tab when you're ready to code