Easily convert your CommonJS (require, module.exports) code into modern ES Modules (import, export) with this simple CLI tool powered by jscodeshift.
✅ Converts module.exports to export default or named exports.
✅ Transforms require() statements into import statements.
✅ Handles default exports, named exports, and JSON imports.
✅ Resolves relative paths for modules correctly.
✅ Converts __dirname and __filename to ES module-compatible syntax.
✅ Supports both single file and batch processing
npm install @ianfyan/cjs-to-esm -gcjs-to-esm path/to/file.jsFor example, to transform all files in the src/ directory:
cjs-to-esm src/const a = 1;
const b = 2;
module.exports = { a, b };const a = 1;
const b = 2;
export { a, b };const fs = require('fs');
const { Server } = require('socket.io');import fs from 'fs';
import socketIo from 'socket.io';
const { Server } = socketIo;const path = require('path');
const myDirname = path.resolve(__dirname, '../src/template');import path from 'path';
import { fileURLToPath } from 'url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const myDirname = path.resolve(__dirname, '../src/template');const packageJson = require('../package.json');import packageJson from '../package.json' with { type: 'json' };Clone the repository:
git clone https://github.com/ianfyan/cjs-to-esm.git
cd cjs-to-esm
npm installTo test all functions:
npm convert path/to/file.jsMIT License - Free to use and modify.