Modules: Organizing Code with ES Modules

1. Welcome and Icebreaker:

  • If you could organize any part of your life into neat modules, what would you choose?

2. Outline the Session:

  • We’ll learn about modules in TypeScript: how to organize code into separate files using ES modules.
  • Learning Outcomes: Understand how to create, import, and export modules for better code organization.
  • Let’s modularize our code!

3. Concept Explanation:

  • Modules allow you to split your code into separate files, making it easier to manage and reuse.
  • TypeScript uses ES module syntax: import and export.
  • Each file is its own module. You can export variables, functions, classes, or interfaces from one file and import them into another.
  • Syntax:
    // math.ts
    export function add(a: number, b: number): number {
      return a + b;
    }
    // main.ts
    import { add } from './math';
    console.log(add(2, 3));
    

4. Live Coding Demonstration:

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

// main.ts
import { multiply } from './math';
console.log(multiply(4, 5)); // 20

// Exporting variables and classes
export const PI = 3.14;
export class Circle {
  constructor(public radius: number) {}
  area() {
    return PI * this.radius * this.radius;
  }
}

// Importing everything
import * as MathUtils from './math';
console.log(MathUtils.PI);

5. Tasks:

  • Short Exercise:
    1. Create a file greetings.ts that exports a function sayHello(name: string): string.
    2. Create a file app.ts that imports and uses sayHello.
    3. Try exporting and importing a class from one file to another.
    4. Use import * as syntax to import all exports from a module.