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

Requiring ESM from CJS

The limitations of using require() with ES Modules and why dynamic import() is necessary.

Requiring ESM from CJS

You'll learn why CommonJS's require() cannot load ES Modules and what to do instead.

The One-Way Street Problem

When you try to use require() to load an ES Module from a CommonJS file, you'll hit a wall. Node.js will throw an error like ERR_REQUIRE_ESM. This happens because CommonJS's require() is synchronous—it expects to load and return a module immediately. ES Modules, however, are asynchronous by design. They support features like top-level await, which means they can't guarantee instant execution.

Think of it like trying to fit a streaming video (ESM) into a DVD player (CJS) that expects everything packaged and ready to play immediately. The formats are fundamentally incompatible.

The Solution: Dynamic Import

Since require() is synchronous but ES Modules are asynchronous, you must use dynamic import instead:

// This FAILS in a .cjs file:
// const myModule = require('./es-module.mjs');

// This WORKS:
async function loadModule() {
  const myModule = await import('./es-module.mjs');
  console.log(myModule.someExport);
}

loadModule();

Dynamic import() returns a Promise, making it compatible with ESM's asynchronous nature. This means you can't use a simple top-level require() anymore—you need to wrap the import in an async function or use .then().

Why This Matters

This limitation is intentional. It prevents blocking synchronous code from accidentally depending on potentially slow asynchronous module initialization. The design forces you to acknowledge and handle the asynchronous nature explicitly.

Key Takeaway: You cannot use require() to load ES Modules in CommonJS—use dynamic import() instead, which returns a Promise and handles ESM's asynchronous loading properly.