moduloze icon indicating copy to clipboard operation
moduloze copied to clipboard

Improper handling of "module.exports" in ESM conversion

Open getify opened this issue 4 years ago • 0 comments

module.exports = {
    x: () => 42
};

module.exports.x();
mz -e
// Error: Error: Multiple default exports not allowed in the same module (./test.js)

This error comes from the fact that currently, the ESM code treats all expression occurrences (not just assignments) of module.exports as a "default exports", and then it errors if you have more than one of those "default exports".

Need to add smarter handling, like this:

let_exp = {
   x: () => 42
};
export default _exp;

_exp.x();

The let _exp assignment-indirection should only be added if there's more than one module.exports reference. Otherwise, it should still be the more minimized form:

export default {
   x: () => 42
};

module.exports = {
    x: () => 42
};

Object.assign(module.exports,{ y: 42 });
mz -e
// Error: Error: Multiple default exports not allowed in the same module (./test.js)

Same thing as above. Should be:

let_exp = {
   x: () => 42
};
export default _exp;

Object.assign(_exp,{ y: 42 });

Need to be careful not to break this pattern, though:

module.exports = {
   x: () => 42
};
module.exports.x = () => 42;

That pattern is used to do both default and named exports, and should still end up as:

export default {
   x: () => 42
};

let _exp = () => 42;
export { _exp as x };

NOT:

var _exp = {
   x: () => 42
};
export default _exp;

_exp.x = () => 42;

getify avatar Jun 30 '21 00:06 getify