esmod

raw JSON →
1.0.0 verified Fri May 01 auth: no javascript

esmod is a fast in-place transpiler for converting ES6 import/export statements to CommonJS require/exports. Version 1.0.0 is currently stable, with a focus on speed by leveraging AST-based transformation rather than regex-only approaches. It distinguishes itself from tools like esbuild or Babel by being designed for lightweight, single-file transformations without module resolution or bundling — ideal for build tool authors and custom pipelines.

error TypeError: Cannot read properties of undefined (reading 'code')
cause Calling transform() without waiting for a Promise, but it's actually synchronous and returns an object directly.
fix
Access result.code immediately after calling transform() without await.
error SyntaxError: Unexpected token 'export'
cause Input contains export statements but options.from is not set to 'esm', so transform treats input as CommonJS.
fix
Set { from: 'esm' } in options.
error Error: No transform applied because source and target are the same.
cause Both from and to options are set to 'esm', resulting in no transformation.
fix
Set 'to' to 'cjs' to convert to CommonJS.
gotcha transform() throws synchronous errors; do not use try/catch with async error patterns.
fix Wrap in try/catch (not .catch()) since it's not a Promise.
gotcha Input code must contain only valid ES module syntax; mixing require() and import will cause parse errors.
fix Ensure code is pure ES module syntax before passing to transform.
deprecated options.from and options.to are optional; default is ESM-to-ESM (no-op), which may be unexpected.
fix Always specify both targets to avoid accidental no-op.
npm install esmod
yarn add esmod
pnpm add esmod

Converts an ES module file (.mjs) to CommonJS (.cjs) using esmod's transform function with explicit source and target formats.

import { transform } from 'esmod';
import { readFileSync, writeFileSync } from 'fs';

const code = readFileSync('input.mjs', 'utf8');
const result = transform(code, { from: 'esm', to: 'cjs' });
writeFileSync('output.cjs', result.code);
console.log('Transformed successfully!');