ADVERTISEMENT
Google AdSense Slot (headerLeaderboard)

Set your Publisher ID in src/config/ads.ts to display live ads.

Node.js Tutorial• 7 min read

Module Systems: CommonJS vs ES Modules

Understanding require/module.exports and modern import/export syntax

Node.js historically used the CommonJS (CJS) module system (require / module.exports). Modern Node.js provides full native support for ECMAScript Modules (ESM) (import / export).

Comparing CJS and ESM in Node.js

CommonJS (CJS): Synchronous module loading using const fs = require('fs') and module.exports = { ... }.

ES Modules (ESM): Static, asynchronous loading using import fs from 'node:fs' and export default ....

Enabling ESM: Add "type": "module" in your package.json, or use the .mjs file extension.

Native protocol prefix: Always prefer prefixing core modules with node: (e.g., node:fs, node:path, node:crypto) for security and clarity.

ESM Module Syntax (mathService.js & index.js)
// mathService.js
export function calculateTax(subtotal, rate = 0.08) {
  return subtotal * rate;
}

export const CURRENCY = 'USD';

// index.js
import { calculateTax, CURRENCY } from './mathService.js';

const orderTotal = 250;
const tax = calculateTax(orderTotal);
console.log(`Total Tax: ${tax} ${CURRENCY}`);
Named exports allow selective importing, enabling tree-shaking and cleaner dependencies.
ADVERTISEMENT
Google AdSense Slot (inContentBanner)

Set your Publisher ID in src/config/ads.ts to display live ads.

Test Yourself With Exercise

+15 XP

Which field in package.json informs Node.js to treat all .js files as ECMAScript Modules (ESM)?