Skip to content

Commit 6f81f16

Browse files
fix: duplicate CommonJS exports
1 parent f8a801a commit 6f81f16

2 files changed

Lines changed: 31 additions & 0 deletions

File tree

packages/plugin-vite/src/plugins/commonjs.ts

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,28 @@ export function cjsPlugin(
3333

3434
if (body.length === 0 && state.get(HAS_ES_MODULE)) {
3535
path.pushContainer("body", t.exportNamedDeclaration(null));
36+
} else {
37+
const seen = new Set<string>();
38+
39+
const children = path.get("body");
40+
for (let i = children.length - 1; i >= 0; i--) {
41+
const child = children[i];
42+
if (child.isExportNamedDeclaration()) {
43+
if (
44+
t.isVariableDeclaration(child.node.declaration) &&
45+
child.node.declaration.declarations.length > 0 &&
46+
t.isIdentifier(child.node.declaration.declarations[0].id)
47+
) {
48+
const name = child.node.declaration.declarations[0].id.name;
49+
50+
if (seen.has(name)) {
51+
child.remove();
52+
} else {
53+
seen.add(name);
54+
}
55+
}
56+
}
57+
}
3658
}
3759
},
3860
},

packages/plugin-vite/src/plugins/commonjs_test.ts

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -165,6 +165,15 @@ var a = _mod.default ?? _mod,
165165
});
166166
});
167167

168+
Deno.test("commonjs - duplicate exports", () => {
169+
runTest({
170+
input: `Object.defineProperty(exports, "__esModule", { value: true });
171+
exports.trace = void 0;
172+
exports.trace = 'foo'`,
173+
expected: `export let trace = 'foo';`,
174+
});
175+
});
176+
168177
// I've never seen this, seems rare. Skipping for now.
169178
Deno.test.ignore("commonjs - require", () => {
170179
runTest({

0 commit comments

Comments
 (0)