Course contentsShow
← JavaScript
Lesson 1545 of 2,72333. JavaScript in Node.jsFree lesson

require() from ESM: Why It Fails

Learn why require() is not available in ES modules and alternatives like createRequire().

require() from ESM: Why It Fails

You'll learn why require() doesn't work in ES modules and discover the workaround when you really need it.

The Problem

When you try to use require() inside an ES module file, Node.js throws an error: ReferenceError: require is not defined. This is intentional, not a bug.

ES modules and CommonJS are two separate module systems with different designs. require() is a CommonJS-specific function that Node.js injects into every CommonJS module. But ES modules don't get this injection—they use import statements instead, which are parsed before code runs and work fundamentally differently.

Think of it like trying to use a Windows program on a Mac. They're different operating systems with different rules. Similarly, require() belongs to the CommonJS "operating system," and ESM doesn't provide it by default.

Why Not Just Support Both?

ES modules are statically analyzable—the imports are determined before any code executes. require() is dynamic—it runs during execution. Mixing both would break the guarantees that make ESM powerful for tree-shaking, circular dependency handling, and module optimization.

The Solution: createRequire()

If you absolutely need require() functionality in an ES module (for example, to load JSON files on older Node versions), Node.js provides createRequire():

import { createRequire } from 'module';
const require = createRequire(import.meta.url);

const data = require('./config.json');

This creates a require function bound to your module's location, letting you use CommonJS-style loading when necessary.

Key Takeaway: require() fails in ES modules because they're a different module system with static imports; use createRequire() if you need CommonJS-style dynamic loading in ESM code.