Why convert MJS to CJS?
People convert to .CJS to run code in older Node.js setups or tools that expect CommonJS, or to ship a require-compatible build alongside an ESM one. The logic stays the same; only the module wiring changes.
How to convert MJS to CJS
esbuild EASIEST
Run esbuild input.mjs --format=cjs --platform=node --outfile=output.cjs to emit CommonJS. Add --bundle if you also want dependencies inlined.
Babel OPEN-SOURCE
Add @babel/plugin-transform-modules-commonjs to your config, then run babel input.mjs -o output.cjs to rewrite imports to require.
Rollup FREE
Set output.format to cjs in rollup.config.js and build; Rollup emits a CommonJS bundle from your ESM entry.
About these formats
An .mjs file is JavaScript source code that Node.js treats as an ECMAScript module, meaning it uses import and export instead of CommonJS require. The extension exists so Node can tell ES…
Open .MJS details →A .CJS file is a data file used by specific software.
Open .CJS details →Quality & what to watch
- Top-level
awaithas no CommonJS equivalent and will fail to convert. - Named exports become properties on
module.exports, and interop with default exports can differ subtly. - Relative
importpaths andimport.meta.urlmay need adjusting for the CommonJS output.
Frequently asked questions
Can I convert by hand?
import x from 'y' for const x = require('y') and export for module.exports.Why did my build fail?
await, which CommonJS cannot express; move it inside an async function.Do I need to rename to .cjs?
package.json has "type": "module"; the .cjs extension forces Node to treat it as CommonJS.