mkdist icon indicating copy to clipboard operation
mkdist copied to clipboard

cjs format should not replace "exports.default =" to "module.exports = " when "exports.default =" in last line

Open gaoletian opened this issue 1 year ago • 3 comments

a reproduction or simple code @pi0

https://github.com/gaoletian/mkdist-issues-192

// src/Foo.ts
export enum Type {
    Foo,
    Bar
}

export default class Action {}
// dist/Foo.js
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
module.exports = exports.Type = void 0;
var Type = exports.Type = /* @__PURE__ */(Type2 => {
  Type2[Type2["Foo"] = 0] = "Foo";
  Type2[Type2["Bar"] = 1] = "Bar";
  return Type2;
})(Type || {});
class Action {}
module.exports = Action;
// test.js
const foo = require('./dist/Foo');
console.log(foo);
console.log(foo.Type);
$ node test.js
foo =  [class Action]
foo.Type = undefined

Hi! 👋

Firstly, thanks for your work on this project! 🙂

Today I used patch-package to patch [email protected] for the project I'm working on.

Here is the diff that solved my problem:

diff --git a/node_modules/mkdist/dist/index.mjs b/node_modules/mkdist/dist/index.mjs
index 1403db8..7b1582a 100644
--- a/node_modules/mkdist/dist/index.mjs
+++ b/node_modules/mkdist/dist/index.mjs
@@ -59,7 +59,9 @@ const jsLoader = async (input, { options }) => {
   }
   const isCjs = options.format === "cjs";
   if (isCjs) {
-    contents = jiti("").transform({ source: contents, retainLines: false }).replace(/^exports.default = /gm, "module.exports = ").replace(/^var _default = exports.default = /gm, "module.exports = ").replace("module.exports = void 0;", "");
+    contents = jiti("")
+      .transform({ source: contents, retainLines: false })
+      .replace("module.exports = void 0;", "");
   }
   let extension = isCjs ? ".js" : ".mjs";
   if (options.ext) {

This issue body was partially generated by patch-package.

gaoletian avatar Jan 08 '24 11:01 gaoletian