JavaScript and TypeScript course Β· Module 5: Advanced JavaScript
ES Modules (import/export)
In this lesson11
Welcome back to Jurassic Park! After building solid JavaScript foundations and learning asynchronous techniques, it's time to explore how to organize code into larger, scalable projects. In a world as complex as Jurassic Park, we need a well-organized structure to ensure system safety and efficiency.
Code Modularization in JavaScript
Imagine managing Jurassic Park without dividing it into teams and departments - everything would be chaotic and dangerous! The same is true for code - when everything lives in one file, it quickly becomes unreadable and hard to maintain.
ES Modules (ECMAScript Modules) is the standard JavaScript module system that allows you to:
- Split code into smaller, more manageable pieces
- Control which elements are accessible outside a module
- Define dependencies between different parts of a program
Exporting Elements from Modules
Let's start by creating a few basic modules for our Jurassic Park management system:
1. Default Export
When we have one primary element to export, we use a default export:
// dinosaur.js - Dinosaur model
class Dinosaur {
constructor(name, species, diet, dangerLevel) {
this.name = name;
this.species = species;
this.diet = diet;
this.dangerLevel = dangerLevel;
this.health = 100;
this.isContained = true;
}
feed() {
this.health = Math.min(100, this.health + 20);
return `${this.name} has been fed. Health level: ${this.health}%`;
}
checkStatus() {
return {
name: this.name,
health: this.health,
isContained: this.isContained,
warning: this.dangerLevel > 7 ? "HIGH DANGER LEVEL" : ""
};
}
}
// Default export - only one class/function/object per file
export default Dinosaur;2. Named Exports
When we have multiple elements to export, we use named exports:
// securityUtils.js - Security utility functions
export const SECURITY_LEVELS = {
GREEN: "normal",
YELLOW: "elevated",
ORANGE: "high",
RED: "critical"
};
export function checkFenceStatus(sectorId) {
// Simulate checking fence status in a given sector
const status = Math.random() > 0.1 ? "active" : "failure";
return {
sector: sectorId,
status,
timestamp: new Date().toISOString()
};
}
export function triggerAlarm(sector, reason) {
console.log(`ALARM! Sector ${sector}: ${reason}`);
// Alarm activation logic
return {
success: true,
alarmId: "ALR-" + Math.floor(Math.random() * 10000)
};
}
// We can also export a default function alongside named exports
export default function getSecurityStatus() {
// Returns overall park security status
return {
level: SECURITY_LEVELS.GREEN,
activeAlarms: 0,
lastChecked: new Date().toISOString()
};
}3. Exporting Previously Defined Variables
We can also define our variables, functions, or classes first and export them at the end of the file:
// parkStats.js - Jurassic Park statistics
const totalVisitors = 0;
const revenue = 0;
const incidents = [];
function addVisitors(count) {
totalVisitors += count;
return totalVisitors;
}
function addRevenue(amount) {
revenue += amount;
return revenue;
}
function recordIncident(type, location, description) {
const incident = {
id: incidents.length + 1,
type,
location,
description,
timestamp: new Date().toISOString()
};
incidents.push(incident);
return incident;
}
function getDailyStats() {
return {
totalVisitors,
revenue,
incidentCount: incidents.length
};
}
// Export multiple elements at once
export {
addVisitors,
addRevenue,
recordIncident,
getDailyStats
};
// We can also rename an exported element
export { recordIncident as logParkIncident };Importing Elements from Modules
After creating modules, it's time to use them in the main application:
1. Default Import
// app.js
import Dinosaur from './dinosaur.js';
// Create new dinosaur instances
const trex = new Dinosaur("Rex", "Tyrannosaurus", "carnivore", 9);
const brachi = new Dinosaur("Longneck", "Brachiosaurus", "herbivore", 4);
console.log(trex.checkStatus());
console.log(brachi.feed());2. Named Import
// securityMonitor.js
import { checkFenceStatus, triggerAlarm, SECURITY_LEVELS } from './securityUtils.js';
// Use imported functions and constants
function monitorSecurity() {
const sectors = ["A1", "B2", "C3", "D4"];
// Check each sector
sectors.forEach(sector => {
const fenceStatus = checkFenceStatus(sector);
if (fenceStatus.status === "failure") {
const alarmResult = triggerAlarm(
sector,
"Electric fence failure!"
);
console.log(`Alarm ${alarmResult.alarmId} triggered in sector ${sector}`);
document.querySelector("#securityStatus").textContent = SECURITY_LEVELS.RED;
}
});
}
setInterval(monitorSecurity, 60000); // Check every minute3. Default and Named Import Together
// dashboard.js
import getSecurityStatus, { SECURITY_LEVELS, checkFenceStatus } from './securityUtils.js';
// Use the default import
const parkStatus = getSecurityStatus();
console.log("Security status:", parkStatus.level);
// Use the named imports
if (parkStatus.level === SECURITY_LEVELS.RED) {
// Check all sectors immediately
["A1", "B2", "C3", "D4"].forEach(sector => {
console.log(`Checking sector ${sector}: `, checkFenceStatus(sector));
});
}4. Import with Alias
// incidentReport.js
import { recordIncident as logIncident } from './parkStats.js';
// Use the imported function under its new name
function reportEmergency(location, details) {
logIncident("EMERGENCY", location, details);
// Additional emergency handling logic
}5. Import Everything as an Object
// adminPanel.js
import * as ParkStats from './parkStats.js';
// Access all module functions through the object
function generateDailyReport() {
const visitorCount = ParkStats.addVisitors(120); // Adds 120 visitors
const dailyRevenue = ParkStats.addRevenue(15000); // Adds $15,000 revenue
const stats = ParkStats.getDailyStats();
return `
Jurassic Park Daily Report:
- Visitor count: ${stats.totalVisitors}
- Revenue: $${stats.revenue}
- Incidents: ${stats.incidentCount}
`;
}Aggregating and Re-exporting Modules
In large projects, it's often useful to create entry points that aggregate and re-export functionality from multiple smaller modules:
// models/index.js - Aggregate all models
export { default as Dinosaur } from './dinosaur.js';
export { default as Employee } from './employee.js';
export { default as Facility } from './facility.js';
export { default as Visitor } from './visitor.js';This lets us import all models from a single entry point:
// main.js
import { Dinosaur, Employee, Facility } from './models/index.js';
// Now we can use all models
const rex = new Dinosaur("Rex", "Tyrannosaurus", "carnivore", 9);
const lab = new Facility("InGen Labs", "B3", 12);
const scientist = new Employee("Dr. Wu", "Chief Geneticist", "lab");Dynamic Module Importing
ES Modules also offer a dynamic import mechanism, allowing modules to be loaded on demand:
// emergencySystem.js
async function handleEmergency(type) {
let emergencyModule;
switch(type) {
case "dinosaurEscape":
emergencyModule = await import('./emergencies/dinosaurEscape.js');
break;
case "powerOutage":
emergencyModule = await import('./emergencies/powerOutage.js');
break;
case "weatherAlert":
emergencyModule = await import('./emergencies/weatherAlert.js');
break;
default:
emergencyModule = await import('./emergencies/generalEmergency.js');
}
// Execute emergency procedure from the loaded module
emergencyModule.initiateProtocol();
}
// UI button to trigger the emergency procedure
document.querySelector("#emergencyButton").addEventListener("click", () => {
const emergencyType = document.querySelector("#emergencyType").value;
handleEmergency(emergencyType);
});ES Modules in the Browser
To use ES Modules directly in the browser, we must add the type="module" attribute to the script tag:
<!DOCTYPE html>
<html>
<head>
<title>Jurassic Park Control Panel</title>
</head>
<body>
<h1>Jurassic Park Control Panel</h1>
<div id="securityStatus"></div>
<select id="emergencyType">
<option value="dinosaurEscape">Dinosaur escape</option>
<option value="powerOutage">Power outage</option>
<option value="weatherAlert">Weather alert</option>
</select>
<button id="emergencyButton">Activate emergency procedure</button>
<!-- Main script using modules -->
<script type="module" src="./app.js"></script>
</body>
</html>Benefits of a Modular Approach
Organizing applications with ES Modules offers many benefits:
- Encapsulation - each module has its own namespace, preventing naming conflicts
- Reusability - modules can be easily reused in different parts of the application
- Organization - code is easier to understand and maintain when split into logical parts
- Team collaboration - different team members can work on separate modules
- Lazy loading - modules can be loaded only when they are needed
- Better dependency management - clearly defined dependencies between modules
Practical Example: Dinosaur Monitoring System
Let's see how we might organize a larger dinosaur monitoring system for Jurassic Park using modules:
// models/dinosaur.js
export default class Dinosaur {
// ... Dinosaur class implementation (as above)
}
// services/dinoTracking.js
import Dinosaur from '../models/dinosaur.js';
export async function getAllDinosaurs() {
// Fetch dinosaur data from API
const response = await fetch('/api/dinosaurs');
const data = await response.json();
// Convert raw data to Dinosaur class instances
return data.map(dino => new Dinosaur(
dino.name,
dino.species,
dino.diet,
dino.dangerLevel
));
}
export async function getDinosaursByDangerLevel(level) {
const allDinos = await getAllDinosaurs();
return allDinos.filter(dino => dino.dangerLevel >= level);
}
// services/securitySystem.js
export async function getActiveFences() {
// Fetch active fence data
const response = await fetch('/api/fences/active');
return response.json();
}
export async function activateSectorLockdown(sectorId) {
// Activate lockdown in a given sector
const response = await fetch(`/api/sectors/${sectorId}/lockdown`, {
method: 'POST'
});
return response.json();
}
// utils/alertSystem.js
export const ALERT_LEVELS = {
INFO: 'info',
WARNING: 'warning',
DANGER: 'danger',
CRITICAL: 'critical'
};
export function showAlert(message, level = ALERT_LEVELS.INFO) {
const alertElement = document.createElement('div');
alertElement.className = `alert alert-${level}`;
alertElement.textContent = message;
document.querySelector('#alertContainer').appendChild(alertElement);
// Remove alert after 5 seconds (unless it's critical)
if (level !== ALERT_LEVELS.CRITICAL) {
setTimeout(() => {
alertElement.remove();
}, 5000);
}
}
// controllers/monitoringDashboard.js
import { getAllDinosaurs, getDinosaursByDangerLevel } from '../services/dinoTracking.js';
import { getActiveFences, activateSectorLockdown } from '../services/securitySystem.js';
import { showAlert, ALERT_LEVELS } from '../utils/alertSystem.js';
export async function initializeDashboard() {
try {
// Fetch dinosaur data and fence status
const [allDinos, activeFences] = await Promise.all([
getAllDinosaurs(),
getActiveFences()
]);
// Find dangerous dinosaurs
const dangerousDinos = await getDinosaursByDangerLevel(8);
// Display data on the dashboard
renderDinosaurTable(allDinos);
renderSecurityStatus(activeFences);
// Show alerts for dangerous dinosaurs
if (dangerousDinos.length > 0) {
showAlert(
`WARNING: ${dangerousDinos.length} dinosaurs with high danger level`,
ALERT_LEVELS.WARNING
);
}
// Set up emergency event listeners
setupEmergencyHandlers();
} catch (error) {
showAlert(`Dashboard initialization error: ${error.message}`, ALERT_LEVELS.DANGER);
}
}
function renderDinosaurTable(dinosaurs) {
// Dinosaur table rendering logic
}
function renderSecurityStatus(fences) {
// Security status rendering logic
}
function setupEmergencyHandlers() {
// Emergency event handler setup logic
document.querySelector('#emergencyLockdown').addEventListener('click', async () => {
const sector = document.querySelector('#sectorSelect').value;
try {
await activateSectorLockdown(sector);
showAlert(`Sector ${sector} lockdown activated`, ALERT_LEVELS.WARNING);
} catch (error) {
showAlert(`Failed to activate lockdown: ${error.message}`, ALERT_LEVELS.CRITICAL);
}
});
}
// app.js - Main application file
import { initializeDashboard } from './controllers/monitoringDashboard.js';
// Initialize application when DOM is ready
document.addEventListener('DOMContentLoaded', () => {
initializeDashboard();
// Additional initialization logic
console.log('Jurassic Park monitoring system started');
});Browser Support and Webpack Configuration
Modern browsers support ES Modules natively, but for full compatibility with older browsers, we often use tools like Webpack or Rollup to bundle our modules into code compatible with older browsers.
Basic Webpack Configuration for ES Modules
// webpack.config.js
const path = require('path');
module.exports = {
entry: './src/app.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env']
}
}
}
]
}
};Best Practices for Working with Modules
- Single responsibility - each module should have one clearly defined responsibility
- Small modules - keep modules small and focused on a specific task
- Consistent naming - use consistent naming conventions for module files
- Explicit dependencies - all dependencies should be clearly defined in imports
- Minimize state mutation - avoid modifying global state in modules
- Documentation - add JSDoc comments to exported functions and classes
- Folder structure - organize modules into a logical folder structure (e.g. models, services, utils)
Summary
ES Modules is a powerful JavaScript code organization mechanism that allows you to create modular, well-organized applications. In a world as complex as Jurassic Park, where every mistake can have catastrophic consequences, good code organization is critical to maintaining safety and efficiency.
In the next exercise we'll look at an alternative module system - CommonJS, which is widely used in the Node.js environment, ideal for building the server-side part of our Jurassic Park management system.
Code for this lesson: main.js
// ES Modules in Jurassic Park
// Main park management system file
console.log("Jurassic Park Management System");
console.log("ES Modules demo (import/export)\n");
// ===========================================
// Simulated imports (in real ES6 these would be separate files)
// ===========================================
// === dinosaur.js - Dinosaur model ===
class Dinosaur {
constructor(name, species, diet, dangerLevel) {
this.name = name;
this.species = species;
this.diet = diet;
this.dangerLevel = dangerLevel; // 1-10
this.isActive = true;
this.lastFed = new Date();
this.energy = 100;
}
feed() {
this.energy = Math.min(100, this.energy + 20);
this.lastFed = new Date();
return `${this.name} has been fed. Energy: ${this.energy}%`;
}
roar() {
const sounds = {
'carnivore': 'ROAAAAR!',
'herbivore': 'Hoooonk!',
'omnivore': 'Grrrrooo!'
};
return `${this.name}: ${sounds[this.diet] || 'Hmm?'}`;
}
getInfo() {
return {
name: this.name,
species: this.species,
diet: this.diet,
dangerLevel: this.dangerLevel,
energy: this.energy,
status: this.isActive ? 'Active' : 'Sleeping'
};
}
}
// Default export
const DinosaurClass = Dinosaur;
// === security.js - Security system ===
const SECURITY_LEVELS = {
GREEN: 1,
YELLOW: 2,
ORANGE: 3,
RED: 4,
CRITICAL: 5
};
function calculateSecurityLevel(dinosaurs) {
const maxDanger = Math.max(...dinosaurs.map(d => d.dangerLevel));
const activeCarnivores = dinosaurs.filter(d => d.diet === 'carnivore' && d.isActive).length;
if (maxDanger >= 9 || activeCarnivores >= 3) return SECURITY_LEVELS.CRITICAL;
if (maxDanger >= 7 || activeCarnivores >= 2) return SECURITY_LEVELS.RED;
if (maxDanger >= 5 || activeCarnivores >= 1) return SECURITY_LEVELS.ORANGE;
if (maxDanger >= 3) return SECURITY_LEVELS.YELLOW;
return SECURITY_LEVELS.GREEN;
}
function getSecurityMessage(level) {
const messages = {
[SECURITY_LEVELS.GREEN]: "Park safe",
[SECURITY_LEVELS.YELLOW]: "Elevated vigilance",
[SECURITY_LEVELS.ORANGE]: "Medium threat",
[SECURITY_LEVELS.RED]: "High threat",
[SECURITY_LEVELS.CRITICAL]: "CRITICAL CONDITION"
};
return messages[level] || "Unknown level";
}
// Named exports
const SecurityModule = {
SECURITY_LEVELS,
calculateSecurityLevel,
getSecurityMessage
};
// === enclosure.js - Paddock management ===
class Enclosure {
constructor(id, name, capacity, type) {
this.id = id;
this.name = name;
this.capacity = capacity;
this.type = type; // 'carnivore', 'herbivore', 'mixed'
this.dinosaurs = [];
this.isLocked = true;
this.maintenanceMode = false;
}
addDinosaur(dinosaur) {
if (this.dinosaurs.length >= this.capacity) {
return `Error: Paddock ${this.name} is full`;
}
if (this.type === 'carnivore' && dinosaur.diet !== 'carnivore') {
return `Error: Paddock for carnivores cannot accept ${dinosaur.diet}`;
}
if (this.type === 'herbivore' && dinosaur.diet === 'carnivore') {
return `Error: Paddock for herbivores cannot accept carnivores`;
}
this.dinosaurs.push(dinosaur);
return `${dinosaur.name} added to paddock ${this.name}`;
}
removeDinosaur(dinosaurName) {
const index = this.dinosaurs.findIndex(d => d.name === dinosaurName);
if (index === -1) {
return `Error: Dinosaur ${dinosaurName} is not in this paddock`;
}
const removed = this.dinosaurs.splice(index, 1)[0];
return `${removed.name} removed from paddock ${this.name}`;
}
feedAll() {
const results = this.dinosaurs.map(dinosaur => dinosaur.feed());
return results;
}
getStatus() {
return {
id: this.id,
name: this.name,
capacity: this.capacity,
occupied: this.dinosaurs.length,
type: this.type,
isLocked: this.isLocked,
maintenanceMode: this.maintenanceMode,
dinosaurs: this.dinosaurs.map(d => d.getInfo())
};
}
lock() {
this.isLocked = true;
return `Paddock ${this.name} closed`;
}
unlock() {
this.isLocked = false;
return `Paddock ${this.name} opened`;
}
}
const EnclosureClass = Enclosure;
// === utils.js - Helper functions ===
function formatTime(date) {
return date.toLocaleTimeString('en-US');
}
function generateId() {
return 'ID-' + Math.random().toString(36).substr(2, 9).toUpperCase();
}
function logAction(action, details = '') {
const timestamp = formatTime(new Date());
const logEntry = `[${timestamp}] ${action} ${details}`;
console.log(logEntry);
return logEntry;
}
function calculateDistance(point1, point2) {
const dx = point2.x - point1.x;
const dy = point2.y - point1.y;
return Math.sqrt(dx * dx + dy * dy);
}
// Exporting many functions
const UtilsModule = {
formatTime,
generateId,
logAction,
calculateDistance
};
// === park-manager.js - Main management system ===
class ParkManager {
constructor() {
this.enclosures = new Map();
this.dinosaurs = new Map();
this.securityLevel = SecurityModule.SECURITY_LEVELS.GREEN;
this.isOpen = false;
this.visitors = 0;
}
// Paddock management
createEnclosure(name, capacity, type) {
const id = UtilsModule.generateId();
const enclosure = new EnclosureClass(id, name, capacity, type);
this.enclosures.set(id, enclosure);
UtilsModule.logAction('ENCLOSURE_CREATED', `${name} (capacity: ${capacity}, type: ${type})`);
return enclosure;
}
// Dinosaur management
addDinosaur(name, species, diet, dangerLevel, enclosureId) {
const dinosaur = new DinosaurClass(name, species, diet, dangerLevel);
this.dinosaurs.set(name, dinosaur);
if (enclosureId && this.enclosures.has(enclosureId)) {
const enclosure = this.enclosures.get(enclosureId);
const result = enclosure.addDinosaur(dinosaur);
UtilsModule.logAction('DINOSAUR_ADDED', `${name} -> ${enclosure.name}`);
console.log(result);
}
this.updateSecurityLevel();
return dinosaur;
}
// Security level update
updateSecurityLevel() {
const allDinosaurs = Array.from(this.dinosaurs.values());
this.securityLevel = SecurityModule.calculateSecurityLevel(allDinosaurs);
const message = SecurityModule.getSecurityMessage(this.securityLevel);
UtilsModule.logAction('SECURITY_UPDATE', message);
}
// Park status report
getParkStatus() {
const enclosureStatuses = Array.from(this.enclosures.values()).map(e => e.getStatus());
const dinosaurCount = this.dinosaurs.size;
const securityMessage = SecurityModule.getSecurityMessage(this.securityLevel);
return {
isOpen: this.isOpen,
visitors: this.visitors,
dinosaurCount,
enclosureCount: this.enclosures.size,
securityLevel: this.securityLevel,
securityMessage,
enclosures: enclosureStatuses,
timestamp: UtilsModule.formatTime(new Date())
};
}
// Opening/closing the park
openPark() {
if (this.securityLevel <= SecurityModule.SECURITY_LEVELS.YELLOW) {
this.isOpen = true;
UtilsModule.logAction('PARK_OPENED', 'Park open for visitors');
return "Jurassic Park is open!";
} else {
return "Park cannot be opened - danger level too high";
}
}
closePark() {
this.isOpen = false;
this.visitors = 0;
UtilsModule.logAction('PARK_CLOSED', 'Park closed');
return "Jurassic Park closed";
}
// Feeding all dinosaurs
feedAllDinosaurs() {
const results = [];
for (const enclosure of this.enclosures.values()) {
const feedResults = enclosure.feedAll();
results.push(...feedResults);
}
UtilsModule.logAction('MASS_FEEDING', `Fed ${results.length} dinosaurs`);
return results;
}
// Emergency
emergencyProtocol() {
UtilsModule.logAction('EMERGENCY', 'Emergency protocol activated!');
// Close park
this.closePark();
// Close all paddocks
for (const enclosure of this.enclosures.values()) {
enclosure.lock();
}
console.log("EMERGENCY PROTOCOL ACTIVATED!");
console.log("- Park closed");
console.log("- All paddocks locked");
console.log("- Guest evacuation in progress");
return "Emergency protocol activated";
}
}
// ===========================================
// SYSTEM DEMO
// ===========================================
console.log("=== PARK SYSTEM INITIALIZATION ===\n");
// Creating the park manager
const parkManager = new ParkManager();
// Creating paddocks
console.log("Creating paddocks...");
const carnivorePaddock = parkManager.createEnclosure("Paddock A - Carnivores", 3, "carnivore");
const herbivorePaddock = parkManager.createEnclosure("Paddock B - Herbivores", 5, "herbivore");
const mixedPaddock = parkManager.createEnclosure("Paddock C - Mixed", 4, "mixed");
console.log("\nAdding dinosaurs...");
// Adding dinosaurs
const trex = parkManager.addDinosaur(
"Rexy",
"Tyrannosaurus Rex",
"carnivore",
9,
carnivorePaddock.id
);
const raptor1 = parkManager.addDinosaur(
"Blue",
"Velociraptor",
"carnivore",
7,
carnivorePaddock.id
);
const raptor2 = parkManager.addDinosaur(
"Charlie",
"Velociraptor",
"carnivore",
7,
carnivorePaddock.id
);
const trice = parkManager.addDinosaur(
"Spike",
"Triceratops",
"herbivore",
3,
herbivorePaddock.id
);
const brachi = parkManager.addDinosaur(
"Gentle Giant",
"Brachiosaurus",
"herbivore",
2,
herbivorePaddock.id
);
const stego = parkManager.addDinosaur(
"Spike Jr",
"Stegosaurus",
"herbivore",
4,
mixedPaddock.id
);
// Testing dinosaur sounds
console.log("\nCommunication test with the dinosaurs:");
console.log(trex.roar());
console.log(raptor1.roar());
console.log(trice.roar());
console.log(brachi.roar());
// Park status report
console.log("\nPARK STATUS REPORT:");
const status = parkManager.getParkStatus();
console.log(`Status: ${status.isOpen ? 'Open' : 'Closed'}`);
console.log(`Dinosaurs: ${status.dinosaurCount}`);
console.log(`Paddocks: ${status.enclosureCount}`);
console.log(`Security: ${status.securityMessage}`);
// Attempting to open park
console.log("\nAttempting to open park...");
const openResult = parkManager.openPark();
console.log(openResult);
// Feeding dinosaurs
console.log("\nFeeding dinosaurs...");
const feedingResults = parkManager.feedAllDinosaurs();
feedingResults.forEach(result => console.log(" " + result));
// Emergency simulation
console.log("\nSimulating a failure...");
setTimeout(() => {
console.log("\nDANGER DETECTED!");
parkManager.emergencyProtocol();
// Status after the failure
setTimeout(() => {
console.log("\nStatus after the emergency protocol:");
const finalStatus = parkManager.getParkStatus();
console.log(`Park: ${finalStatus.isOpen ? 'Open' : 'Closed'}`);
console.log(`Security: ${finalStatus.securityMessage}`);
console.log("\nPaddock details:");
finalStatus.enclosures.forEach(enc => {
console.log(` ${enc.name}: ${enc.occupied}/${enc.capacity} dinosaurs, ${enc.isLocked ? 'Closed' : 'Open'}`);
});
}, 2000);
}, 3000);
// ===========================================
// DEMO OF DIFFERENT EXPORT TYPES
// ===========================================
console.log("\n=== ES6 EXPORT TYPES ===");
// 1. Default export - one main thing from a module
console.log("1. Default export - main Dinosaur class");
const myDino = new DinosaurClass("Test Dino", "Test Species", "omnivore", 5);
console.log(" Created:", myDino.name);
// 2. Named exports - many functions/objects
console.log("\n2. Named exports - utility functions");
console.log(" Generated ID:", UtilsModule.generateId());
console.log(" Current time:", UtilsModule.formatTime(new Date()));
// 3. Re-exports - exporting from other modules
console.log("\n3. Security module exports");
console.log(" Security levels:", Object.keys(SecurityModule.SECURITY_LEVELS));
// 4. Namespace import - everything as one object
console.log("\n4. Combined module usage:");
const testEnclosure = new EnclosureClass("TEST-001", "Test Enclosure", 2, "mixed");
testEnclosure.addDinosaur(myDino);
console.log(" Test enclosure created with:", testEnclosure.dinosaurs.length, "dinosaur(s)");
// ===========================================
// SIMULATION OF REAL ES6 IMPORTS
// ===========================================
console.log("\n=== SIMULATION OF ES6 IMPORTS ===");
console.log("In a real application we would use:");
console.log("");
console.log("// main.js");
console.log("import Dinosaur from './dinosaur.js'; // default import");
console.log("import { SECURITY_LEVELS, calculateSecurityLevel } from './security.js'; // named imports");
console.log("import * as Utils from './utils.js'; // namespace import");
console.log("import Enclosure, { EnclosureType } from './enclosure.js'; // mixed import");
console.log("");
console.log("// dinosaur.js");
console.log("export default class Dinosaur { ... }");
console.log("");
console.log("// security.js");
console.log("export const SECURITY_LEVELS = { ... };");
console.log("export function calculateSecurityLevel(dinosaurs) { ... }");
console.log("");
console.log("// utils.js");
console.log("export function formatTime(date) { ... }");
console.log("export function generateId() { ... }");
console.log("export { formatTime as timeFormatter }; // alias export");
console.log("\nES Modules demo completed!");Docs entries used in this lesson
Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. What is a module in JavaScript?
Hands-on tasks in the game
- Horizontal ordering
Arrange the module import elements: