Lessons in this course (11)

2. Modules — CommonJS vs ES modules, npm and package.json

Basic★ Must knowLesson 2 of 11
js
// CommonJS (default for .js unless "type": "module")
const path = require('node:path');
module.exports = { add: (a, b) => a + b };

// ES modules (.mjs, or "type": "module" in package.json)
import path from 'node:path';
import { readFile } from 'node:fs/promises';
export function add(a, b) { return a + b; }
export default add;
CommonJSES modules
Syntaxrequire / module.exportsimport / export
LoadingSynchronous, at runtimeStatic analysis, async loading, top-level await
__dirnameAvailableUse import.meta.dirname (Node 20.11+)
InteropCan require() ESM since Node 22 (sync graphs)Can import CommonJS
json
{
  "name": "shop-api",
  "version": "1.0.0",
  "type": "module",
  "main": "src/server.js",
  "engines": { "node": ">=22" },
  "scripts": {
    "dev": "node --watch src/server.js",
    "start": "node src/server.js",
    "test": "node --test",
    "lint": "eslint ."
  },
  "dependencies": { "express": "^5.1.0", "mssql": "^11.0.1", "zod": "^3.24.0" },
  "devDependencies": { "eslint": "^9.0.0", "supertest": "^7.0.0" }
}
  • dependencies ship to production; devDependencies only for development/build.
  • Semantic versioning: ^5.1.0 allows 5.x.x updates, ~5.1.0 allows 5.1.x, exact 5.1.0 pins.
  • package-lock.json records exact installed versions — commit it; use npm ci in CI for reproducible installs.
  • npm audit checks known vulnerabilities; npm outdated shows updates.