Modules
CommonJS require/exports, ES Modules import/export, and Node's module resolution
Skills taught: node.commonjs, node.esmodules, node.module-resolution, node.builtin-modules
CommonJS vs ES Modules
// ── CommonJS (default in Node.js) ──
// Importing — synchronous
const fs = require('fs'); // built-in module
const path = require('path'); // built-in module
const utils = require('./utils'); // local file (./utils.js)
const lodash = require('lodash'); // npm package
// Exporting — two ways
// 1. module.exports — replaces the entire export object
module.exports = function greet(name) {
return `Hello, ${name}!`;
};
// 2. exports.x — adds to the export object
exports.PI = 3.14159;
exports.add = (a, b) => a + b;
exports.subtract = (a, b) => a - b;
// Note: don't mix both — module.exports replaces exports
// ── ES Modules (.mjs or "type": "module" in package.json) ──
// Named imports
import { readFile, writeFile } from 'node:fs/promises';
import { join, dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
// Default import
import express from 'express'; // most npm packages export a default
// __dirname equivalent in ESM:
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
// Named exports
export const PI = 3.14159;
export function add(a, b) { return a + b; }
export class Calculator {
multiply(a, b) { return a * b; }
}
// Default export
export default function greet(name) {
return `Hello, ${name}!`;
}
// Dynamic import — works anywhere, even in CJS
const mod = await import('./heavy-module.mjs'); // loaded on demand
Frequently Asked Questions
How do I switch a Node.js project to ES Modules?
Add `"type": "module"` to your package.json. Then rename .js files to .mjs, or leave them as .js (the type field makes all .js files ESM). Change require() to import and module.exports to export. Replace __dirname and __filename with: `const __dirname = dirname(fileURLToPath(import.meta.url))`.