Course contentsShow
← JavaScript
Lesson 1429 of 2,72331. ModulesFree lesson

Dynamic Import vs require()

Comparing dynamic import's promise-based approach with CommonJS's synchronous require() for runtime loading.

Dynamic Import vs require()

You'll learn: How dynamic import() differs from CommonJS's require() when loading modules at runtime.

Two Ways to Load Modules On-Demand

Both dynamic import() and require() let you load modules at runtime (not just at the top of your file), but they work fundamentally differently.

require() is synchronous — it blocks execution until the module is fully loaded and ready. It's like waiting at a store checkout: you can't leave until the transaction completes.

// CommonJS (Node.js) - blocks here
const module = require('./myModule.js');
console.log(module.data); // runs after module loads

Dynamic import() is promise-based — it returns a promise immediately and loads the module asynchronously. It's like ordering online: you get a tracking number instantly and continue your day while delivery happens in the background.

// ES Modules - returns immediately
import('./myModule.js')
  .then(module => {
    console.log(module.data);
  });

// Or with async/await
const module = await import('./myModule.js');
console.log(module.data);

Key Differences

Blocking behavior: require() freezes your program until loading completes. Dynamic import() never blocks — perfect for web applications where freezing the UI is unacceptable.

Error handling: require() throws synchronous errors (use try/catch immediately). Dynamic import() rejects promises (use .catch() or try/catch with await).

Environment: require() is Node.js (CommonJS). Dynamic import() works in both browsers and modern Node.js (ES Modules).

When it matters: For large modules in browsers, dynamic import() prevents blocking the main thread. For small Node.js scripts, require() is simpler if you don't mind blocking.

Key Takeaway: Use dynamic import() for non-blocking, promise-based module loading (especially in browsers); require() blocks synchronously and belongs to the older CommonJS system.