JavaScript and TypeScript course ยท Module 5: Advanced JavaScript

Dynamic Module Importing

14 min read ยท
In this lesson7

In the previous exercises we learned about two main JavaScript module systems: ES Modules and CommonJS. Both systems allow organizing code into independent modules, but we mainly dealt with static imports. Now we'll go to the next level - dynamic module importing, which gives us much greater flexibility.

For our Jurassic Park management system, dynamic imports can be crucial. Imagine needing different emergency procedures depending on what's happening - a T-Rex escape requires a different set of actions than a power outage or an approaching hurricane!

Introduction to Dynamic Importing

Dynamic module importing allows loading modules during program execution, rather than during its initialization. This means we can load a module exactly when it's needed, saving memory and load time for modules that may never be used.

Dynamic Import Syntax

Dynamic import uses the import() function, which returns a Promise containing the loaded module:

// Static import (always loaded)
import { DinosaurTracker } from './dinosaurTracker.js';

// Dynamic import (loaded on demand)
import('./emergencyProcedures.js')
  .then(module => {
    // Now we can use the loaded module
    module.initializeEmergencyProtocol();
  })
  .catch(error => {
    console.error('Failed to load emergency procedures:', error);
  });

It's even more convenient to use dynamic imports with async/await:

async function handleEmergency(type) {
  try {
    // Dynamically import the appropriate emergency procedure module
    const emergencyModule = await import(`./emergencies/${type}.js`);

    // Use the loaded module
    return emergencyModule.executeProtocol();
  } catch (error) {
    console.error(`Failed to load procedure: ${type}`, error);
    // Fall back to the general emergency procedure
    const fallbackModule = await import('./emergencies/general.js');
    return fallbackModule.executeProtocol();
  }
}

// Use our function
handleEmergency('dinosaurEscape').then(result => {
  console.log('Emergency procedure status:', result);
});

Dynamic Importing Applications in Jurassic Park

Let's think about practical applications of dynamic importing in our Jurassic Park management system:

1. Load on Demand

We can load functionality only when needed, which is especially useful for rarely used but large modules:

// dashboardController.js
async function loadDashboard(dashboardType) {
  // Base dashboard always loaded
  const statusPanel = document.getElementById('statusPanel');
  statusPanel.innerHTML = 'Loading...';

  try {
    // Dynamically import the requested dashboard type
    const dashboardModule = await import(`./dashboards/${dashboardType}Dashboard.js`);

    // Initialize the dashboard
    const dashboard = new dashboardModule.default();
    await dashboard.initialize(statusPanel);

    console.log(`Dashboard ${dashboardType} loaded successfully`);
  } catch (error) {
    console.error(`Error loading dashboard ${dashboardType}: `, error);
    statusPanel.innerHTML = `Dashboard loading error: ${error.message}`;
  }
}

// Interface buttons
document.getElementById('btnDinosaurs').addEventListener('click', () => {
  loadDashboard('dinosaurs');
});

document.getElementById('btnSecurity').addEventListener('click', () => {
  loadDashboard('security');
});

document.getElementById('btnVisitors').addEventListener('click', () => {
  loadDashboard('visitors');
});

2. Different Implementations for Different Environments

We can dynamically load different implementations depending on the environment (production, development, testing):

async function initializeTracking() {
  const environment = process.env.NODE_ENV || 'development';

  try {
    // Load the appropriate implementation for the environment
    const trackingModule = await import(`./tracking/${environment}.js`);

    // Initialize the tracking system
    const tracker = trackingModule.createTracker();
    tracker.initialize();

    return tracker;
  } catch (error) {
    console.error(`Failed to initialize tracking for environment ${environment}: `, error);
    // Fall back to the development version
    const fallbackModule = await import('./tracking/development.js');
    return fallbackModule.createTracker();
  }
}

// Using the function
initializeTracking().then(tracker => {
  tracker.trackEvent('app_initialized', { timestamp: Date.now() });
});

3. Lazy Loading of Interface Components

In a frontend application we can delay loading interface components to speed up the initial page load:

// dynamicComponents.js
export async function loadComponent(componentName) {
  try {
    const module = await import(`./components/${componentName}.js`);
    return module.default;
  } catch (error) {
    console.error(`Failed to load component ${componentName}: `, error);
    throw error;
  }
}

// In the main application file
import { loadComponent } from './dynamicComponents.js';

document.getElementById('btnShowMap').addEventListener('click', async () => {
  try {
    // Load the park map only when the user needs it
    const ParkMap = await loadComponent('ParkMap');
    const mapContainer = document.getElementById('mapContainer');

    const parkMap = new ParkMap({
      container: mapContainer,
      initialZoom: 2,
      centerCoordinates: [34.5, 12.8]
    });

    parkMap.render();
  } catch (error) {
    alert(`Failed to load map: ${error.message}`);
  }
});

4. Dynamic Loading of Security Procedures and Protocols

One of the most important applications in our park will be the security procedures system:

// securitySystem.js
export class SecuritySystem {
  constructor() {
    this.activeProtocols = new Map();
    this.alertLevel = 'green';
  }

  async activateProtocol(protocolName, params = {}) {
    try {
      // Check if the protocol is already active
      if (this.activeProtocols.has(protocolName)) {
        console.log(`Protocol ${protocolName} is already active`);
        return this.activeProtocols.get(protocolName);
      }

      // Dynamically import the protocol
      const protocolModule = await import(`./protocols/${protocolName}.js`);

      // Initialize the protocol
      const protocol = new protocolModule.default(params);
      await protocol.initialize();

      // Add to active protocols
      this.activeProtocols.set(protocolName, protocol);

      console.log(`Protocol ${protocolName} activated successfully`);
      return protocol;
    } catch (error) {
      console.error(`Error activating protocol ${protocolName}: `, error);
      throw new Error(`Failed to activate protocol ${protocolName}: ${error.message}`);
    }
  }

  async deactivateProtocol(protocolName) {
    const protocol = this.activeProtocols.get(protocolName);
    if (!protocol) {
      console.log(`Protocol ${protocolName} is not active`);
      return false;
    }

    try {
      await protocol.shutdown();
      this.activeProtocols.delete(protocolName);
      console.log(`Protocol ${protocolName} deactivated successfully`);
      return true;
    } catch (error) {
      console.error(`Error deactivating protocol ${protocolName}: `, error);
      return false;
    }
  }

  async handleEmergency(type, location) {
    console.log(`Handling emergency: ${type} at location ${location}`);

    // Update alert level
    this.alertLevel = 'red';

    try {
      // Import the appropriate emergency procedure
      const emergencyModule = await import(`./emergencies/${type}.js`);

      // Run the procedure
      const procedure = new emergencyModule.EmergencyProcedure(location);
      const emergencyId = await procedure.execute();

      console.log(`Emergency procedure for ${type} initiated, ID: ${emergencyId}`);
      return emergencyId;
    } catch (error) {
      console.error(`Failed to handle emergency ${type}: `, error);

      // Fall back to general emergency procedure
      try {
        const generalModule = await import('./emergencies/general.js');
        const procedure = new generalModule.EmergencyProcedure(location, { originalType: type });
        return procedure.execute();
      } catch (fallbackError) {
        console.error(`Critical error! Even the general procedure failed: `, fallbackError);
        return null;
      }
    }
  }
}

// Using the security system
const security = new SecuritySystem();

// Example protocol activation
document.getElementById('btnLockdown').addEventListener('click', async () => {
  try {
    const protocol = await security.activateProtocol('lockdown', {
      sectors: ['A1', 'B2'],
      reason: 'Dinosaur escape'
    });

    document.getElementById('status').textContent = `Lockdown protocol active in ${protocol.affectedSectors.length} sectors`;
  } catch (error) {
    alert(`Protocol activation error: ${error.message}`);
  }
});

// Example emergency reporting
async function reportEmergency(type, location) {
  try {
    const emergencyId = await security.handleEmergency(type, location);
    return emergencyId;
  } catch (error) {
    console.error(`Failed to report emergency: `, error);
    return null;
  }
}

Example Module Implementations

Let's see what some of the dynamically imported modules in our system might look like:

Example Security Protocol (lockdown.js)

// protocols/lockdown.js
export default class LockdownProtocol {
  constructor(params) {
    this.sectors = params.sectors || [];
    this.reason = params.reason || 'Unknown reason';
    this.timestamp = new Date();
    this.active = false;
    this.affectedSectors = [];
  }

  async initialize() {
    console.log(`Initializing lockdown protocol for sectors: ${this.sectors.join(', ')}`);

    // Simulate lockdown activation for each sector
    this.affectedSectors = await Promise.all(
      this.sectors.map(async (sector) => {
        try {
          // In a real system, this would be an API call
          await this.activateSectorLockdown(sector);
          return {
            sector,
            status: 'secured',
            securedAt: new Date()
          };
        } catch (error) {
          console.error(`Sector ${sector} lockdown error: `, error);
          return {
            sector,
            status: 'failed',
            error: error.message
          };
        }
      })
    );

    this.active = true;

    // Return status
    return {
      active: this.active,
      affectedSectors: this.affectedSectors,
      initializedAt: new Date()
    };
  }

  async shutdown() {
    if (!this.active) {
      return { success: false, reason: 'Protocol not active' };
    }

    console.log(`Deactivating lockdown protocol for sectors: ${this.sectors.join(', ')}`);

    // Simulate lockdown deactivation for each sector
    await Promise.all(
      this.sectors.map(async (sector) => {
        try {
          // In a real system, this would be an API call
          await this.deactivateSectorLockdown(sector);
        } catch (error) {
          console.error(`Error unlocking sector ${sector}: `, error);
        }
      })
    );

    this.active = false;

    return {
      success: true,
      deactivatedAt: new Date()
    };
  }

  // Method simulating sector lockdown activation
  async activateSectorLockdown(sector) {
    return new Promise((resolve, reject) => {
      // Simulate network delay and API response
      setTimeout(() => {
        if (Math.random() > 0.1) {
          resolve({
            sector,
            status: 'secured',
            gates: { closed: 4, total: 4 },
            fences: { energized: true }
          });
        } else {
          reject(new Error(`Sector ${sector} lockdown error: System failure`));
        }
      }, 500 + Math.random() * 1000);
    });
  }

  // Method simulating sector lockdown deactivation
  async deactivateSectorLockdown(sector) {
    return new Promise((resolve, reject) => {
      // Simulate network delay and API response
      setTimeout(() => {
        if (Math.random() > 0.05) {
          resolve({
            sector,
            status: 'unlocked',
            gates: { closed: 0, total: 4 },
            fences: { energized: true } // Fences remain energized
          });
        } else {
          reject(new Error(`Error unlocking sector ${sector}: System failure`));
        }
      }, 300 + Math.random() * 700);
    });
  }
}

Example Emergency Procedure (dinosaurEscape.js)

// emergencies/dinosaurEscape.js
export class EmergencyProcedure {
  constructor(location, options = {}) {
    this.location = location;
    this.options = options;
    this.id = 'EM-' + Date.now().toString(36).toUpperCase();
    this.status = 'initialized';
    this.startTime = new Date();
  }

  async execute() {
    console.log(`Executing emergency procedure for dinosaur escape at location ${this.location}`);
    this.status = 'in_progress';

    try {
      // 1. Activate zone alarm
      await this.activateZoneAlarm(this.location);

      // 2. Evacuate visitors from the threatened area
      await this.evacuateVisitors(this.location);

      // 3. Dispatch security team
      const securityTeam = await this.dispatchSecurityTeam(this.location);

      // 4. Activate lockdown protocol in this and adjacent sectors
      const adjacentSectors = await this.getAdjacentSectors(this.location);
      const allSectors = [this.location, ...adjacentSectors];
      await this.activateLockdown(allSectors);

      // 5. Notify staff
      await this.notifyStaff({
        type: 'dinosaur_escape',
        location: this.location,
        securityTeam,
        sectors: allSectors
      });

      this.status = 'completed';
      console.log(`Emergency procedure ${this.id} completed successfully`);

      return this.id;
    } catch (error) {
      this.status = 'failed';
      console.error(`Emergency procedure ${this.id} failed: `, error);
      throw error;
    }
  }

  // Helper methods...
  async activateZoneAlarm(zone) {
    console.log(`Activating alarm in zone ${zone}`);
    return { success: true, zone };
  }

  async evacuateVisitors(zone) {
    console.log(`Evacuating visitors from zone ${zone}`);
    return { success: true, evacuatedCount: Math.floor(Math.random() * 50) + 10 };
  }

  async dispatchSecurityTeam(zone) {
    console.log(`Dispatching security team to zone ${zone}`);
    return {
      teamId: 'ST-' + Math.floor(Math.random() * 10) + 1,
      members: Math.floor(Math.random() * 5) + 3,
      estimatedArrival: new Date(Date.now() + 5 * 60 * 1000)
    };
  }

  async getAdjacentSectors(sector) {
    // In a real system, we'd fetch this from a database
    const sectorMap = {
      'A1': ['A2', 'B1'],
      'A2': ['A1', 'A3', 'B2'],
      'B1': ['A1', 'B2', 'C1'],
      // ... more mappings
    };

    return sectorMap[sector] || [];
  }

  async activateLockdown(sectors) {
    console.log(`Activating lockdown in sectors: ${sectors.join(', ')}`);

    // Dynamically import the lockdown protocol module
    const LockdownModule = await import('../protocols/lockdown.js');
    const lockdown = new LockdownModule.default({
      sectors,
      reason: 'Dinosaur escape'
    });

    return lockdown.initialize();
  }

  async notifyStaff(data) {
    console.log(`Notifying staff about emergency: `, data);
    return { success: true, notifiedCount: Math.floor(Math.random() * 30) + 5 };
  }
}

Building a Dynamic System with Runtime-Determined Imports

We can also create more advanced systems where import paths are determined at runtime:

// dynamicModuleLoader.js
export class ModuleLoader {
  constructor(basePath = '') {
    this.basePath = basePath;
    this.cache = new Map();
  }

  async load(modulePath, ignoreCache = false) {
    const fullPath = this.basePath ? `${this.basePath}/${modulePath}` : modulePath;

    // Check cache unless cache is ignored
    if (!ignoreCache && this.cache.has(fullPath)) {
      console.log(`Returning module ${fullPath} from cache`);
      return this.cache.get(fullPath);
    }

    try {
      console.log(`Dynamically loading module: ${fullPath}`);
      const module = await import(fullPath);

      // Save to cache
      this.cache.set(fullPath, module);

      return module;
    } catch (error) {
      console.error(`Error loading module ${fullPath}: `, error);
      throw error;
    }
  }

  async loadMultiple(modulePaths) {
    try {
      const modulePromises = modulePaths.map(path => this.load(path));
      return await Promise.all(modulePromises);
    } catch (error) {
      console.error(`Error loading multiple modules: `, error);
      throw error;
    }
  }

  clearCache(modulePath) {
    if (modulePath) {
      const fullPath = this.basePath ? `${this.basePath}/${modulePath}` : modulePath;
      return this.cache.delete(fullPath);
    } else {
      // Clear entire cache
      this.cache.clear();
      return true;
    }
  }
}

// DinosaurTrackingSystem.js
import { ModuleLoader } from './dynamicModuleLoader.js';

export class DinosaurTrackingSystem {
  constructor() {
    this.moduleLoader = new ModuleLoader('./dinosaurs');
    this.trackers = new Map();
    this.activeDinosaurs = new Set();
  }

  async initialize() {
    // Load base modules
    const [baseUtils, trackingCore] = await this.moduleLoader.loadMultiple([
      './utils.js',
      './trackingCore.js'
    ]);

    this.utils = baseUtils;
    this.trackingCore = trackingCore;

    console.log(`Dinosaur tracking system initialized.`);
  }

  async trackDinosaur(dinosaurId, species) {
    if (this.trackers.has(dinosaurId)) {
      console.log(`Dinosaur ${dinosaurId} is already being tracked.`);
      return this.trackers.get(dinosaurId);
    }

    try {
      // Dynamically load the tracking module for the given species
      const specificTrackingModule = await this.moduleLoader.load(`./species/${species.toLowerCase()}.js`);

      // Create and initialize a tracker for this dinosaur
      const tracker = new specificTrackingModule.default(dinosaurId, {
        utils: this.utils,
        core: this.trackingCore
      });

      await tracker.initialize();

      // Save the tracker and mark the dinosaur as active
      this.trackers.set(dinosaurId, tracker);
      this.activeDinosaurs.add(dinosaurId);

      console.log(`Started tracking dinosaur ${dinosaurId} (${species}).`);
      return tracker;
    } catch (error) {
      console.error(`Error tracking dinosaur ${dinosaurId}: `, error);

      // If there's no specific module for the species, use the generic one
      try {
        console.log(`Trying generic tracking module for ${species}`);
        const genericTrackingModule = await this.moduleLoader.load('./genericTracker.js');

        const tracker = new genericTrackingModule.default(dinosaurId, species, {
          utils: this.utils,
          core: this.trackingCore
        });

        await tracker.initialize();

        this.trackers.set(dinosaurId, tracker);
        this.activeDinosaurs.add(dinosaurId);

        console.log(`Started generic tracking for dinosaur ${dinosaurId} (${species}).`);
        return tracker;
      } catch (fallbackError) {
        console.error(`Failed to use even the generic tracking module: `, fallbackError);
        throw new Error(`Cannot track dinosaur ${dinosaurId}: ${error.message}`);
      }
    }
  }

  async stopTracking(dinosaurId) {
    if (!this.trackers.has(dinosaurId)) {
      console.log(`Dinosaur ${dinosaurId} is not being tracked.`);
      return false;
    }

    try {
      const tracker = this.trackers.get(dinosaurId);
      await tracker.shutdown();

      this.trackers.delete(dinosaurId);
      this.activeDinosaurs.delete(dinosaurId);

      console.log(`Stopped tracking dinosaur ${dinosaurId}.`);
      return true;
    } catch (error) {
      console.error(`Error stopping tracking for dinosaur ${dinosaurId}: `, error);
      return false;
    }
  }

  getActiveTrackingCount() {
    return this.activeDinosaurs.size;
  }

  getTrackerInfo(dinosaurId) {
    const tracker = this.trackers.get(dinosaurId);
    if (!tracker) {
      return null;
    }

    return {
      dinosaurId,
      species: tracker.species,
      lastKnownLocation: tracker.getLastLocation(),
      status: tracker.getStatus(),
      isActive: tracker.isActive()
    };
  }
}

// Using the tracking system
async function initTrackingSystem() {
  const trackingSystem = new DinosaurTrackingSystem();
  await trackingSystem.initialize();

  // Track different dinosaur species
  try {
    const rexTracker = await trackingSystem.trackDinosaur('rex-01', 'tyrannosaurus');
    console.log('T-Rex status:', rexTracker.getStatus());

    const raptorTracker = await trackingSystem.trackDinosaur('raptor-02', 'velociraptor');
    console.log('Velociraptor status:', raptorTracker.getStatus());

    // Even without a specific module, the system should use the fallback
    const stegoTracker = await trackingSystem.trackDinosaur('stego-01', 'stegosaurus');
    console.log('Stegosaurus status:', stegoTracker.getStatus());

    console.log(`Active tracking: ${trackingSystem.getActiveTrackingCount()} dinosaurs`);
  } catch (error) {
    console.error(`Error initializing tracking system: `, error);
  }
}

// Initialize the system
initTrackingSystem();

Pros and Cons of Dynamic Importing

Pros

  1. Lower initial load - The application loads only those modules needed at any given moment
  2. Better performance - Code splitting allows for faster page loading
  3. Flexibility - Ability to load modules depending on conditions or user interactions
  4. Conditional imports - Ability to choose different implementations depending on environment, parameters, etc.
  5. Easier maintenance - Splitting the application into smaller, independent modules

Cons

  1. Complexity - Adds a layer of complexity to the application
  2. Error handling - Requires careful error handling for cases when a module cannot be loaded
  3. Delays - Loading a module at runtime may introduce delays in the user interface
  4. Increased bundle size - In some cases, it can lead to code duplication
  5. Debugging - Can be harder to debug than static imports

Implementation in Different Environments

Browsers

In modern browsers, dynamic import works natively:

// Browser example
document.getElementById('btnActivateLockdown').addEventListener('click', async () => {
  try {
    const lockdownModule = await import('./security/lockdown.js');
    const lockdown = new lockdownModule.default();
    lockdown.activateForSectors(['A1', 'B2']);
  } catch (error) {
    console.error('Failed to load lockdown module:', error);
  }
});

Node.js

Node.js officially supports dynamic imports since version 13.2.0:

// Node.js example
async function runDinosaurAnalysis(species) {
  try {
    // Dynamic import of the analysis module for the given species
    const analyzer = await import(`./analyzers/${species.toLowerCase()}.js`);
    return analyzer.analyzeGenome();
  } catch (error) {
    console.error(`No analyzer for species ${species}: `, error);
    // Use the generic analyzer
    const genericAnalyzer = await import('./analyzers/generic.js');
    return genericAnalyzer.analyzeGenome(species);
  }
}

// Usage
runDinosaurAnalysis('velociraptor')
  .then(results => console.log('Genome analysis results:', results))
  .catch(error => console.error('Analysis error:', error));

Webpack and Other Bundlers

Bundlers like Webpack, Rollup, or Parcel automatically detect dynamic imports and split code into smaller chunks:

// Webpack will automatically understand and handle this import
const loadAdminPanel = async () => {
  // A separate chunk will be generated for adminPanel
  const adminModule = await import(/* webpackChunkName: "admin" */ './adminPanel');
  return new adminModule.default();
};

// You can even specify loading priority
const prefetchReportGenerator = () => {
  // Fetch the module in advance, but execute only when needed
  import(/* webpackPrefetch: true */ './reportGenerator');
};

Summary

Dynamic module importing is a powerful feature that allows for greater flexibility and performance in JavaScript applications. In the context of our Jurassic Park, it gives us the ability to build systems that can dynamically respond to various situations, which is crucial for the safety of a park full of dangerous dinosaurs!

Thanks to dynamic imports we can:

  • Load modules only when they are needed
  • Choose different implementations depending on context
  • Reduce the initial application load time
  • Create flexible systems with modules determined at runtime

In the next exercise we'll look at JavaScript debugging tools, which will be invaluable when something goes wrong in our park management systems!

Code for this lesson: main.js
// Dynamic module importing - Jurassic Park
// Lazy loading and Code Splitting

console.log("Dynamic Module Importing");
console.log("On-demand loading system\n");

// ===========================================
// DYNAMIC MODULE SIMULATION
// ===========================================

// Simulated modules as functions
const modules = {
  '/modules/trex-handler.js': () => ({
    name: 'T-Rex Handler Module',
    handleTRex: (trex) => {
      console.log(`T-Rex handling: ${trex.name}`);
      console.log(`  Danger level: ${trex.dangerLevel}/10`);
      console.log(`  Status: Double protection required`);
      return {
        securityLevel: 'MAXIMUM',
        requiredGuards: 4,
        specialEquipment: ['Tranquilizer', 'Electric Fence', 'Tracker']
      };
    }
  }),

  '/modules/herbivore-handler.js': () => ({
    name: 'Herbivore Handler Module',
    handleHerbivore: (dino) => {
      console.log(`Herbivore handling: ${dino.name}`);
      console.log(`  Danger level: ${dino.dangerLevel}/10`);
      console.log(`  Status: Standard protection`);
      return {
        securityLevel: 'LOW',
        requiredGuards: 1,
        specialEquipment: ['Food Dispenser', 'Health Monitor']
      };
    }
  }),

  '/modules/raptor-handler.js': () => ({
    name: 'Raptor Handler Module',
    handleRaptor: (raptor) => {
      console.log(`Velociraptor handling: ${raptor.name}`);
      console.log(`  Danger level: ${raptor.dangerLevel}/10`);
      console.log(`  Status: High alert - they hunt in packs!`);
      return {
        securityLevel: 'HIGH',
        requiredGuards: 3,
        specialEquipment: ['Pack Tracker', 'Sound System', 'Emergency Protocol']
      };
    }
  }),

  '/modules/analytics.js': () => ({
    name: 'Analytics Module',
    generateReport: (dinosaurs) => {
      const total = dinosaurs.length;
      const carnivores = dinosaurs.filter(d => d.diet === 'carnivore').length;
      const herbivores = dinosaurs.filter(d => d.diet === 'herbivore').length;
      const avgDanger = dinosaurs.reduce((sum, d) => sum + d.dangerLevel, 0) / total;

      return {
        totalDinosaurs: total,
        carnivores,
        herbivores,
        averageDangerLevel: avgDanger.toFixed(2),
        recommendation: avgDanger > 6 ? 'Increase security' : 'Security level OK'
      };
    }
  }),

  '/modules/emergency.js': () => ({
    name: 'Emergency Protocol Module',
    activateEmergency: (reason) => {
      console.log(`\nEMERGENCY PROTOCOL ACTIVATED!`);
      console.log(`Reason: ${reason}`);
      console.log(`1. Closing all paddocks`);
      console.log(`2. Guest evacuation`);
      console.log(`3. Security team mobilization`);
      return {
        status: 'ACTIVE',
        timestamp: new Date().toISOString(),
        actions: ['LOCK_ENCLOSURES', 'EVACUATE', 'ALERT_SECURITY']
      };
    }
  })
};

// Simulated import() for the demo
async function dynamicImport(path) {
  console.log(`โณ Loading module: ${path}...`);

  // Simulated network delay
  await new Promise(resolve => setTimeout(resolve, 500));

  if (modules[path]) {
    const module = modules[path]();
    console.log(`Loaded: ${module.name}\n`);
    return module;
  }

  throw new Error(`Module not found: ${path}`);
}

// ===========================================
// DINOSAUR MANAGEMENT SYSTEM
// ===========================================

class DinosaurManager {
  constructor() {
    this.dinosaurs = [];
    this.loadedModules = new Map();
  }

  addDinosaur(name, species, diet, dangerLevel) {
    const dinosaur = { name, species, diet, dangerLevel };
    this.dinosaurs.push(dinosaur);
    console.log(`Added dinosaur: ${name} (${species})`);
    return dinosaur;
  }

  async handleDinosaur(dinosaur) {
    console.log(`\nProcessing: ${dinosaur.name}...`);

    // Dynamic loading of appropriate module
    let modulePath;
    let handlerMethod;

    if (dinosaur.species === 'Tyrannosaurus Rex') {
      modulePath = '/modules/trex-handler.js';
      handlerMethod = 'handleTRex';
    } else if (dinosaur.species === 'Velociraptor') {
      modulePath = '/modules/raptor-handler.js';
      handlerMethod = 'handleRaptor';
    } else if (dinosaur.diet === 'herbivore') {
      modulePath = '/modules/herbivore-handler.js';
      handlerMethod = 'handleHerbivore';
    } else {
      console.log(`No dedicated module for ${dinosaur.species}`);
      return null;
    }

    // Check cache
    if (!this.loadedModules.has(modulePath)) {
      const module = await dynamicImport(modulePath);
      this.loadedModules.set(modulePath, module);
    } else {
      console.log(`Used cached module: ${modulePath}\n`);
    }

    const handler = this.loadedModules.get(modulePath);
    return handler[handlerMethod](dinosaur);
  }

  async generateAnalytics() {
    console.log(`\nGenerating the analytics report...`);

    if (!this.loadedModules.has('/modules/analytics.js')) {
      const module = await dynamicImport('/modules/analytics.js');
      this.loadedModules.set('/modules/analytics.js', module);
    }

    const analytics = this.loadedModules.get('/modules/analytics.js');
    return analytics.generateReport(this.dinosaurs);
  }

  async triggerEmergency(reason) {
    const module = await dynamicImport('/modules/emergency.js');
    return module.activateEmergency(reason);
  }
}

// ===========================================
// DEMO
// ===========================================

async function runDemo() {
  console.log("=== DEMO START ===\n");

  const manager = new DinosaurManager();

  // Adding dinosaurs
  console.log("Registering dinosaurs:");
  const trex = manager.addDinosaur('Rexy', 'Tyrannosaurus Rex', 'carnivore', 9);
  const raptor1 = manager.addDinosaur('Blue', 'Velociraptor', 'carnivore', 7);
  const raptor2 = manager.addDinosaur('Charlie', 'Velociraptor', 'carnivore', 7);
  const brachi = manager.addDinosaur('Gentle Giant', 'Brachiosaurus', 'herbivore', 2);
  const trice = manager.addDinosaur('Spike', 'Triceratops', 'herbivore', 3);

  console.log(`\\nTotal number of dinosaurs: ${manager.dinosaurs.length}`);

  // Dynamic module loading for each dinosaur
  console.log("\n=== ON-DEMAND MODULE LOADING ===");

  const trexProtocol = await manager.handleDinosaur(trex);
  console.log('Security protocol:', trexProtocol);

  const raptor1Protocol = await manager.handleDinosaur(raptor1);
  console.log('Security protocol:', raptor1Protocol);

  const raptor2Protocol = await manager.handleDinosaur(raptor2);
  console.log('Security protocol:', raptor2Protocol);

  const brachiProtocol = await manager.handleDinosaur(brachi);
  console.log('Security protocol:', brachiProtocol);

  const triceProtocol = await manager.handleDinosaur(trice);
  console.log('Security protocol:', triceProtocol);

  // Analytics report
  console.log("\n=== ANALYTICS ===");
  const report = await manager.generateAnalytics();
  console.log('\nReport:', JSON.stringify(report, null, 2));

  // Emergency
  if (parseFloat(report.averageDangerLevel) > 6) {
    const emergency = await manager.triggerEmergency('High average danger level');
    console.log('\nEmergency status:', emergency);
  }

  console.log(`\nLoaded modules: ${manager.loadedModules.size}`);
  console.log(`List: ${Array.from(manager.loadedModules.keys()).join(', ')}`);

  console.log("\n=== BENEFITS OF DYNAMIC IMPORTS ===\n");
  console.log("Lazy Loading:");
  console.log("   - Modules loaded only when needed");
  console.log("   - Faster application startup\n");

  console.log("Code Splitting:");
  console.log("   - Smaller initial bundle");
  console.log("   - Better memory usage\n");

  console.log("Conditional Loading:");
  console.log("   - Loading based on runtime conditions");
  console.log("   - Flexibility in resource management\n");

  console.log("Caching:");
  console.log("   - Once loaded, module is cached");
  console.log("   - Faster access on subsequent calls\n");

  console.log("=== SYNTAX ===\n");
  console.log("// A dynamic import returns a Promise");
  console.log("import('./module.js')");
  console.log("  .then(module => {");
  console.log("    module.doSomething();");
  console.log("  })");
  console.log("  .catch(err => console.error(err));\n");

  console.log("// Or with async/await");
  console.log("async function loadModule() {");
  console.log("  const module = await import('./module.js');");
  console.log("  module.doSomething();");
  console.log("}\n");

  console.log("Demo completed!");
}

// Run the demo
runDemo().catch(console.error);

Docs entries used in this lesson

Spotted a mistake in this lesson?

Hands-on tasks in the game

  • Click in order

    Arrange the default export elements in the correct order:

  • Click in order

    Arrange the JavaScript module export elements:

  • Horizontal ordering

    Arrange the JavaScript module import elements:

  1. Click in orderES Module Export Syntax
  2. Click in orderModule Export Syntax
  3. Put in orderModule Import Syntax

Useful articles