Difference Between Require and Import in Node.js
This article explains the key differences between the
require and import syntax in Node.js. It
covers their underlying module systems, loading mechanisms, syntax
rules, and performance implications to help you decide which one to use
in your JavaScript projects.
CommonJS (require) vs. ES Modules (import)
The fundamental difference between require and
import is that they belong to two distinct module
systems:
requireis part of the CommonJS (CJS) module system, which was built into Node.js by default from its inception.importis part of the ES Modules (ESM) system, which is the official, standardized module system for JavaScript (standardized in ES6/ES2015).
1. Synchronous vs. Asynchronous Loading
require()is synchronous. When Node.js encounters arequirestatement, it pauses execution, reads the file from the disk, compiles it, and executes it before moving on to the next line of code.importis asynchronous. ES Modules are designed to work in both browsers and servers. The module structure is analyzed and resolved during the compilation phase before any code is executed. This allows for non-blocking, parallel loading of dependencies.
2. Dynamic vs. Static Loading
requireallows dynamic loading. Because it is executed at runtime, you can placerequirestatements inside conditional blocks (likeifstatements) or functions.if (condition) { const module = require('./myModule'); }importis static.importstatements must be declared at the top level of your file. They cannot be placed insideifstatements or functions. (Note: Modern JavaScript does support a dynamicimport()function for on-demand loading, which returns a promise, but the standardimportstatement remains strictly static).
3. Strict Mode
requiredoes not enforce strict mode ("use strict") by default; you must opt into it manually at the top of your files.importautomatically enforces strict mode in all modules. You do not need to declare"use strict"at the beginning of files using ES Modules.
4. Syntax and Exporting Differences
The way modules are exported and imported differs significantly between the two systems.
CommonJS
(require and module.exports)
To export in CommonJS:
// math.js
const add = (a, b) => a + b;
module.exports = { add };To import in CommonJS:
const { add } = require('./math');ES Modules (import
and export)
To export in ES Modules:
// math.js
export const add = (a, b) => a + b;To import in ES Modules:
import { add } from './math.js';5. File Extensions and Node.js Execution
Node.js handles these two systems differently based on your project configuration:
- Using
require: Node.js treats files as CommonJS by default. You can userequirein files with the.jsextension without any special configuration. - Using
import: To use ES Modules withimportstatements, you must either add"type": "module"to yourpackage.jsonfile or save your files with the.mjsfile extension.