Node.js Course
Node.js
/
Intermediate

require() vs import

Definition

A technical comparison between CommonJS (`require`) and ES Modules (`import`) focusing on how they parse, execute, and handle dynamic module loading.

Explain Like I'm New

`require` reads a file right on the spot, blocking the code execution until it finishes. `import` is smarter; Node scans the entire file first, finds all the `imports`, links everything together in memory, and *then* executes the code. This is why `import` is strictly placed at the top of a file.

Real World Example

If you try to put an `import` statement inside an `if (userIsAdmin)` block, the app will crash. Imports must be static. But you CAN put `require()` inside an if block to save memory! (Though ES Modules introduced `await import()` for dynamic loading).

Common Use Cases

  • •Refactoring legacy code to modern ESM
  • •Optimizing module loading

Interactive Example

// --- DIFFERENCE 1: Location ---
// IMPORT must be at the absolute top level of the file.
import os from 'os';

const isAdmin = true;

if (isAdmin) {
  // REQUIRE can be dynamic and hidden anywhere in the code.
  // This saves memory if the module is rarely used.
  // const adminUtils = require('./admin-utils'); // (Fails if file is ESM)
  
  // To do this dynamically in ESM, we use Dynamic Imports:
  // import('./admin-utils.js').then(utils => utils.cleanDB());
}

// --- DIFFERENCE 2: Synchronous vs Asynchronous ---
// require() pauses execution until the file is fully loaded.
// import/export allows Node to build a "Module Graph" asynchronously before running.

Interview Questions

basic

  • Can you mix `require` and `import` in the same file?

intermediate

  • What does 'Static Analysis' mean in relation to `import`?

advanced

  • How do you dynamically load an ES Module based on a condition?

Flash Cards

Question

Can you mix them?

Click to reveal answer
Answer

Generally, no. If a file is an ES Module (uses `import`), `require` is disabled. If a file is CommonJS, `import` is disabled. However, an ES Module can dynamically import a CommonJS file.

Question

How do you dynamically load ESM?

Click to reveal answer
Answer

Using the dynamic import function, which returns a Promise: `const module = await import('./heavy-module.js');`. This works inside `if` statements!