Migration planning
Prerequisite: node-engineering-governance. Objective: Map CommonJS to ESM transition. Each example is independent. Use Node.js 22.16.0 in a disposable directory; save as main.mjs and run node main.mjs. No external service is contacted.
How it works
Inventory runtime flags, dependencies, native addons, module mode, CLI entry points and supported environments. For CommonJS-to-ESM, mark files explicitly using .mjs/.cjs or package type. Replace require and exports deliberately; ESM relative imports normally need extensions. Native addon ABI compatibility, Express routing changes and TypeScript build configuration need their own tests. Run existing contract tests before and after each change and maintain rollback compatibility with persistent data.
Compare explicit module entry points
import {writeFileSync} from 'node:fs';import {createRequire} from 'node:module';writeFileSync('legacy.cjs','module.exports={total:(a,b)=>a+b}');writeFileSync('modern.mjs','export const total=(a,b)=>a+b;');const require=createRequire(import.meta.url);const legacy=require('./legacy.cjs');const modern=await import('./modern.mjs');console.log(legacy.total(2,3),modern.total(2,3));Expected output:
5 5The same small contract works through both explicit module modes.
Catch missing ESM extension
import {writeFileSync} from 'node:fs';writeFileSync('util.mjs','export const value=7;');try{await import('./util')}catch(e){console.log(e.code)}console.log((await import('./util.mjs')).value);Expected output:
ERR_MODULE_NOT_FOUND7The explicit file extension fixes this local ESM resolution failure.
Common mistake
Do not combine a major runtime upgrade, framework migration and database schema rewrite into one untested release.
Practice
Plan a staged CommonJS-to-ESM migration of a CLI with a documented output contract and rollback condition.
Reference candidate: node-migration-planning-lookup (route unverified). Original instructional model; independent source review pending.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Migration planning — knowledge check
Apply the lesson to a fresh scenario and explain the evidence boundary.
What does .cjs explicitly select?
What must be checked for native addons?
What should precede migration?