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?