Advertisement
Beginner Node.js, Core Node.js Modules

What is the difference between require() (CommonJS) and import (ES Modules) when loading Node.js's own core modules?

Short answer

require() is synchronous, part of CommonJS; import is part of the ES Module standard, resolved as part of module loading, requiring either a .mjs extension or "type": "module" in package.json -- core modules support both, but a project must be consistent about which system its…

Save Node.js mock interview
Advertisement
AModel answer
require() is synchronous, part of CommonJS; import is part of the ES Module standard, resolved as part of module loading, requiring either a .mjs extension or "type": "module" in package.json -- core modules support both, but a project must be consistent about which system its files use.
// CommonJS
const fs = require('node:fs');
// ES Modules
import fs from 'node:fs';
Real-world example
A team migrating to ES Modules sets "type": "module" in package.json and converts every require() to import, checking remaining CommonJS-only dependencies still load via Node's interop.
Likely follow-ups
  • What's the interop rule for a CommonJS file trying to import an ES Module?
  • Why does an ESM file need dynamic import() to conditionally load a CommonJS module?
Related topics