ts2esm icon indicating copy to clipboard operation
ts2esm copied to clipboard

Fix module.exports object literal transformation to ESM exports

Open Copilot opened this issue 5 months ago • 1 comments

This PR fixes the issue where module.exports = { ... } object literals were being stripped entirely instead of being transformed to proper ESM exports.

Problem

Previously, when transforming CommonJS to ESM, the following pattern would be incorrectly handled:

const c0 = 0;
const c1 = 1;

module.exports = {
  c0,
  c1,
};

Before (incorrect): The entire module.exports statement was stripped, leaving only:

const c0 = 0;
const c1 = 1;

After (correct): Now properly transforms to ESM exports:

const c0 = 0;
const c1 = 1;

export { c0, c1 };

Solution

Enhanced the replaceModuleExports function in src/converter/replacer/replaceModuleExports.ts to handle object literal expressions by:

  1. Detecting object literals: Added support for SyntaxKind.ObjectLiteralExpression alongside existing identifier and function expression handling
  2. Shorthand properties: Transforms { c0, c1 } to export { c0, c1 }
  3. Aliased properties: Transforms { a: valueA, b: valueB } to export { valueA as a, valueB as b }
  4. Mixed properties: Handles combinations like { x, z: y }export { x, y as z }

The implementation uses ts-morph's AST parsing to properly extract property names and values from object literals, generating the appropriate ESM export declarations.

Testing

Added comprehensive test coverage with three new test cases covering all scenarios:

  • Basic shorthand properties
  • Aliased properties
  • Mixed shorthand and aliased properties

All existing tests continue to pass, ensuring backward compatibility.

Fixes #125.


💬 Share your feedback on Copilot coding agent for the chance to win a $200 gift card! Click here to start the survey.

Copilot avatar Aug 09 '25 16:08 Copilot

how do i try this locally?

i have a repo that i want to transform, but #125 makes the entire project unusable, how do i try this fix on my project to test

raprocks avatar Aug 20 '25 06:08 raprocks