In Node.js, you can import modules using either the CommonJS syntax or the ES Module (ESM) syntax, depending on your project setup.
✅ 1. CommonJS (Default in Node.js)
Most Node.js projects use CommonJS by default.
-
Works out of the box in
.js
files. -
Used widely in older Node.js codebases.
✅ 2. ES Modules (ECMAScript Modules)
If your project uses "type": "module"
in package.json
or your file has a .mjs
extension, you can use ESM syntax:
When to Use Which?
Project Type | Use |
---|---|
Traditional Node.js | require() |
Modern, ESM-based | import |
Bundled front-end apps | import (via tools like Webpack, Vite) |