0
0
NodejsComparisonBeginner · 4 min read

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:

Featurerequireimport
Module SystemCommonJSES Modules (ESM)
Syntax TypeFunction callKeyword statement
LoadingSynchronousAsynchronous (static)
Dynamic LoadingYes, can load conditionallyNo, must be static at top level
Support in Node.jsDefault in older versionsNative since v12+, recommended now
File ExtensionsUsually .js or .cjsUsually .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

javascript
const fs = require('fs');

const data = fs.readFileSync('./example.txt', 'utf8');
console.log(data);
Output
Contents of example.txt printed to console
↔️

Import Equivalent

javascript
import fs from 'fs';

const data = await fs.promises.readFile('./example.txt', 'utf8');
console.log(data);
Output
Contents of example.txt printed to console
🎯

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.
Node.js supports both, but import is recommended for modern code.
Use require for legacy or dynamic loading needs.
Use import for new projects and better optimization.