Require vs Import in Node.js: Key Differences and Usage
require is the older CommonJS syntax for loading modules in Node.js, working synchronously and supporting dynamic loading. import is the modern ES Modules syntax, working asynchronously with static analysis, and is the recommended approach in recent Node.js versions.Quick Comparison
Here is a quick side-by-side comparison of require and import in Node.js:
| Feature | require | import |
|---|---|---|
| Module System | CommonJS | ES Modules (ESM) |
| Syntax Type | Function call | Keyword statement |
| Loading | Synchronous | Asynchronous (static) |
| Dynamic Loading | Yes, can load conditionally | No, must be static at top level |
| Support in Node.js | Default in older versions | Native since v12+, recommended now |
| File Extensions | Usually .js or .cjs | Usually .mjs or .js with "type": "module" |
Key Differences
require is part of the CommonJS module system, which Node.js used by default for many years. It loads modules synchronously, meaning the code waits until the module is fully loaded before continuing. This allows dynamic loading, so you can call require inside functions or conditionals.
On the other hand, import is the modern ES Modules syntax standardized in JavaScript. It uses static analysis, so all imports must be declared at the top level and cannot be conditional or dynamic. This enables better optimization and tree shaking by bundlers.
Node.js added native support for ES Modules starting with version 12, but it requires either using the .mjs file extension or setting "type": "module" in package.json. Unlike require, import statements are asynchronous under the hood, though they appear synchronous in syntax.
Code Comparison
const fs = require('fs'); const data = fs.readFileSync('./example.txt', 'utf8'); console.log(data);
Import Equivalent
import fs from 'fs'; const data = await fs.promises.readFile('./example.txt', 'utf8'); console.log(data);
When to Use Which
Choose require when working on legacy Node.js projects or when you need dynamic module loading inside functions or conditionals. It is simpler for quick scripts and fully supported everywhere.
Choose import for modern projects targeting Node.js 12+ or when you want to use the latest JavaScript features and better tooling support. It enables static analysis, improved optimization, and aligns with frontend JavaScript standards.
Key Takeaways
require uses CommonJS and loads modules synchronously with dynamic capability.import uses ES Modules with static, asynchronous loading and must be top-level.import is recommended for modern code.require for legacy or dynamic loading needs.import for new projects and better optimization.