Fix module.exports object literal transformation to ESM exports
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:
-
Detecting object literals: Added support for
SyntaxKind.ObjectLiteralExpressionalongside existing identifier and function expression handling -
Shorthand properties: Transforms
{ c0, c1 }toexport { c0, c1 } -
Aliased properties: Transforms
{ a: valueA, b: valueB }toexport { valueA as a, valueB as b } -
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.
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