Sobes.tech
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 and module.exports or exports for 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 import and export statements.
  • Loads modules asynchronously.
  • Is the standard for newer Node.js versions (starting from 12.0.0 with --experimental-modules flag, fully from 14.0.0 by default with .mjs extension or type: "module" in package.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.

What modularity systems exist in Node.js? — Node.js - sobes.tech