Migrating Node.js to ESM Modules
Intermediatev1.0.0
Step-by-step guide to migrating a Node.js project from CommonJS require() to ECMAScript Modules (ESM) with import/export syntax, including handling edge cases and dependencies.
Content
Overview
ECMAScript Modules (ESM) is the JavaScript standard module system, replacing CommonJS in modern Node.js. This skill walks through converting a CommonJS project to ESM, handling __dirname replacements, JSON imports, and dependency compatibility.
Why This Matters
- -Standard compliance — ESM is the JavaScript module standard, supported everywhere
- -Static analysis — enables tree-shaking and better IDE support
- -Top-level await — use await outside async functions
- -Browser compatibility — same module system as frontend code
- -Future-proof — new Node.js features target ESM first
Step 1: Update package.json
Step 2: Rename Files (If Needed)
Step 3: Replace require() with import
Step 4: Replace module.exports with export
Step 5: Replace __dirname and __filename
Step 6: Handle Dynamic Imports
Best Practices
- -Always use the
node:prefix for built-in modules (node:fs,node:path) - -Add file extensions in import paths:
import { foo } from './utils.js' - -Use
import.meta.urlinstead of__filename - -Use
import.meta.dirname(Node 21.2+) instead of__dirname - -Test your package with both ESM and CommonJS consumers if publishing
Common Mistakes
- -Forgetting to add
.jsextension to relative imports (required in ESM) - -Using
require()in an ESM file (not available — usecreateRequireas escape hatch) - -Not updating test runner configuration for ESM (Jest needs special config)
- -Forgetting that
import()is async — returns a Promise
FAQ
Discussion
Loading comments...