Migrate from CommonJS to ES Modules
Convert a Node.js project from require/module.exports to import/export syntax with proper configuration.
Prerequisites
- -Node.js 16 or later
- -Existing CommonJS project
Steps
Set module type in package.json
Add the type field to package.json to tell Node.js to treat .js files as ES modules by default.
With type: module, all .js files use ESM. Use .cjs extension for files that must remain CommonJS.
Convert require statements to import
Replace require() calls with import statements and module.exports with export.
Fix __dirname and __filename references
Replace __dirname and __filename with ESM equivalents since these globals do not exist in ES modules.
__dirname and __filename are not available in ESM. Every file that uses them needs the import.meta.url workaround.
Add file extensions to relative imports
ESM requires explicit file extensions on relative imports. Update all local import paths.
This is the most tedious part. Every relative import must include .js even if the source file is .ts (TypeScript resolves .js to .ts).
Handle JSON imports
JSON imports require an import assertion in ESM mode.
The createRequire workaround works on all Node.js versions and is useful for packages that only support CommonJS.
Full Script
FAQ
Discussion
Loading comments...