fix(vite): support commonjs module.exports assignment (#3247)

This commit is contained in:
Marvin Hagemeister
2025-08-25 08:48:34 +02:00
committed by GitHub
parent 9975d1698f
commit bf25d10a84
2 changed files with 67 additions and 28 deletions
@@ -54,6 +54,45 @@ export function cjsPlugin(
}
if (exported.size > 0 || exportedNs.size > 0) {
path.unshiftContainer(
"body",
t.expressionStatement(
t.callExpression(
t.memberExpression(
t.identifier("Object"),
t.identifier("defineProperty"),
),
[
t.identifier("module"),
t.stringLiteral("exports"),
t.objectExpression([
t.objectMethod(
"method",
t.identifier("get"),
[],
t.blockStatement([
t.returnStatement(t.identifier("exports")),
]),
),
t.objectMethod(
"method",
t.identifier("set"),
[t.identifier("value")],
t.blockStatement([
t.expressionStatement(
t.assignmentExpression(
"=",
t.identifier("exports"),
t.identifier("value"),
),
),
]),
),
]),
],
),
),
);
path.unshiftContainer(
"body",
t.variableDeclaration("var", [
@@ -63,14 +102,7 @@ export function cjsPlugin(
),
t.variableDeclarator(
t.identifier("module"),
t.objectExpression([
t.objectProperty(
t.identifier("exports"),
t.identifier("exports"),
false,
true,
),
]),
t.objectExpression([]),
),
]),
);
@@ -124,24 +156,11 @@ export function cjsPlugin(
id,
t.logicalExpression(
"??",
t.logicalExpression(
"??",
t.memberExpression(
t.memberExpression(
t.identifier("module"),
t.identifier("exports"),
),
t.identifier("default"),
),
t.memberExpression(
t.identifier("exports"),
t.identifier("default"),
),
),
t.memberExpression(
t.identifier("module"),
t.identifier("exports"),
t.identifier("default"),
),
t.identifier("exports"),
),
),
]),
@@ -14,12 +14,17 @@ function runTest(options: { input: string; expected: string }) {
}
const INIT = `var exports = {},
module = {
exports
};`;
module = {};
Object.defineProperty(module, "exports", {
get() {
return exports;
},
set(value) {
exports = value;
}
});`;
const DEFAULT_EXPORT =
`const _default = module.exports.default ?? exports.default ?? module.exports;`;
const DEFAULT_EXPORT = `const _default = exports.default ?? exports;`;
const DEFAULT_EXPORT_END = `export default _default;`;
Deno.test("commonjs - module.exports default", () => {
@@ -451,3 +456,18 @@ Object.assign(_default, _ns);
${DEFAULT_EXPORT_END}`,
});
});
Deno.test("commonjs - assign module.exports", () => {
runTest({
input: `module.exports = { foo: 1 };`,
expected: `${INIT}
module.exports = {
foo: 1
};
var _foo = exports.foo;
export { _foo as foo };
${DEFAULT_EXPORT}
_default.foo = _foo;
${DEFAULT_EXPORT_END}`,
});
});