Building Your Learning Module...
Getting things ready for you!
Find videos you like?
Save to resource drawer for future reference!
Modules let you split code into separate files and import/export between them. Each module has its own scope, preventing global namespace pollution!
// Export individual items
export const PI = 3.14159;
export const E = 2.71828;
export function add(a, b) {
return a + b;
}
export function subtract(a, b) {
return a - b;
}
export class Calculator {
multiply(a, b) {
return a * b;
}
}// Import specific items
import { PI, add, Calculator } from './math.js';
console.log(PI); // 3.14159
console.log(add(5, 3)); // 8
const calc = new Calculator();
console.log(calc.multiply(4, 5)); // 20
// Import all as object
import * as Math from './math.js';
console.log(Math.PI); // 3.14159
console.log(Math.E); // 2.71828Different ways to export named items (simulated)
// Default export (one per file)
export default class User {
constructor(name) {
this.name = name;
}
greet() {
console.log(`Hi, I'm ${this.name}`);
}
}
// Or with function
export default function createUser(name) {
return { name };
}// Import default (no braces!)
import User from './user.js';
const alice = new User('Alice');
alice.greet(); // Hi, I'm Alice
// Can name it anything
import MyUser from './user.js';
import Person from './user.js';
// Both work - same import!One default export per file (simulated)
📄 utils.js
// Named exports
export const VERSION = '1.0.0';
export function helper() {
return 'Helper function';
}
// Default export
export default function main() {
return 'Main function';
}📄 app.js
// Import both
import main, { VERSION, helper } from './utils.js';
console.log(main()); // Main function
console.log(VERSION); // 1.0.0
console.log(helper()); // Helper functionCombining named and default exports (simulated)
Create barrel exports for easier imports (simulated)
Load modules on demand (simulated)
Multiple exports per fileexport {} const, function, class };import { name } from './file.js';
One per fileexport default class/functionimport name from './file.js';
import * as Name - All as objectimport { x as y } - Renameawait import() - Dynamic
Always include .js in import paths
Relative paths use ./ or ../