Lab 03: Modules & ESM
Overview
Step 1: Named Exports & Imports
// math.mjs — named exports
export const PI = 3.14159265358979;
export function add(a, b) { return a + b; }
export function multiply(a, b) { return a * b; }
export class Vector {
constructor(x, y) { this.x = x; this.y = y; }
magnitude() { return Math.sqrt(this.x ** 2 + this.y ** 2); }
add(other) { return new Vector(this.x + other.x, this.y + other.y); }
}
// main.mjs — named imports
import { PI, add, multiply, Vector } from './math.mjs';
console.log(PI); // 3.14159...
console.log(add(2, 3)); // 5
const v = new Vector(3, 4);
console.log(v.magnitude()); // 5Step 2: Default Exports
Step 3: Namespace Imports & Re-exports
Step 4: Dynamic import()
Step 5: Module Resolution
Step 6: Circular Dependencies
Step 7: CommonJS vs ESM Differences
Step 8: Capstone — Module-Based Utility Library
Summary
Feature
ESM
CommonJS
Last updated
