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

Loading Code Playground...

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!