Skip to content

Commit a67e130

Browse files
authored
fix: faster/more robust commonjs playground plugin (#1381)
Handle some edge cases around default exports, a especially weird code snippet of a specific very popular but abandoned library, and bail in more cases for perf
1 parent 0dd78c6 commit a67e130

File tree

2 files changed

+21
-4
lines changed

2 files changed

+21
-4
lines changed

packages/repl/src/lib/workers/bundler/index.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,8 @@ self.addEventListener('message', async (event: MessageEvent<BundleMessageData>)
7676
can_use_experimental_async
7777
);
7878

79+
console.log('[bundle worker result]', result);
80+
7981
if (JSON.stringify(result.error) === JSON.stringify(ABORT)) return;
8082
if (result && uid === current_id) postMessage(result);
8183
});

packages/repl/src/lib/workers/bundler/plugins/commonjs.ts

Lines changed: 19 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,14 @@ const plugin: Plugin = {
1212
name: 'commonjs',
1313

1414
transform: (code, id) => {
15-
if (!/\b(require|module|exports)\b/.test(code)) return;
15+
if (
16+
id.endsWith('.mjs') ||
17+
id.endsWith('.esm.js') ||
18+
code.startsWith('import ') ||
19+
!/\b(require|module|exports)\b/.test(code)
20+
) {
21+
return;
22+
}
1623

1724
try {
1825
const ast = parse(code, {
@@ -40,9 +47,12 @@ const plugin: Plugin = {
4047
if (node.left.object.type !== 'Identifier' || node.left.object.name !== 'exports') return;
4148
if (node.left.computed || node.left.property.type !== 'Identifier') return;
4249

43-
exports.push(
44-
`export const ${node.left.property.name} = module.exports.${node.left.property.name};`
45-
);
50+
// Default is a special case (and would result in invalid syntax) and kinda fucked up: https://github.com/evanw/esbuild/issues/1719#issuecomment-953470495
51+
if (node.left.property.name !== 'default') {
52+
exports.push(
53+
`export const ${node.left.property.name} = module.exports.${node.left.property.name};`
54+
);
55+
}
4656

4757
context.next();
4858
}
@@ -53,6 +63,11 @@ const plugin: Plugin = {
5363
.map((id, i) => `'${id}': __repl_${i}`)
5464
.join(', ')} };`;
5565

66+
// Special case https://github.com/mathiasbynens/CSS.escape/issues/12
67+
if (id.includes('css.escape')) {
68+
code = code.replace("typeof global != 'undefined' ? global : this", 'globalThis');
69+
}
70+
5671
const transformed = [
5772
imports,
5873
lookup,

0 commit comments

Comments
 (0)