Middle
What modularity systems exist in Node.js?
sobes.tech AI
Answer from AI
CommonJS and ECMAScript Modules (ESM).
CommonJS:
- Uses
require()for importing modules andmodule.exportsorexportsfor exporting. - Loads modules synchronously.
- Was the standard for Node.js versions before 12.0.0.
// CommonJS import
const fs = require('fs');
// CommonJS export
module.exports = {
readFile: fs.readFileSync
};
ECMAScript Modules (ESM):
- Uses
importandexportstatements. - Loads modules asynchronously.
- Is the standard for newer Node.js versions (starting from 12.0.0 with
--experimental-modulesflag, fully from 14.0.0 by default with.mjsextension ortype: "module"inpackage.json).
// ESM import
import fs from 'fs';
// ESM export
export const readFile = fs.readFileSync;
Comparison:
| Feature | CommonJS | ESM |
|---|---|---|
| Import | require() |
import |
| Export | module.exports, exports |
export |
| Loading | Synchronous | Asynchronous |
| Syntax | Dynamic (can be inside conditions) | Static (top-level only) |
Note: ESM support in Node.js is evolving, and some features may vary depending on version and configuration.