Skip to content

Commit cb72001

Browse files
committed
fix(build): fix CommonJS export script edge cases
Fixed two issues in fix-commonjs-exports.mjs: 1. Stray semicolons after comment placeholders - Now properly consumes the semicolon when replacing module.exports statement - Prevents: `/* module.exports will be set at end of file */;` 2. Double module prefix in module.exports.default - Skip transformation when 'exports.default' is already preceded by 'module.' - Prevents: `module.module.exports` (was incorrectly transforming `module.exports.default`) These fixes ensure external dependencies like yoctocolors-cjs export correctly and modules with export default work without errors.
1 parent 5bddd43 commit cb72001

File tree

1 file changed

+25
-3
lines changed

1 file changed

+25
-3
lines changed

scripts/fix-commonjs-exports.mjs

Lines changed: 25 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -225,11 +225,25 @@ async function processDirectory(dir, verbose = false) {
225225
}
226226
s.remove(exportCallStart, removeEnd)
227227

228-
// Replace module.exports = __toCommonJS(name) with comment placeholder
229-
// We'll add the actual export at the end of the file
228+
// Replace the entire statement: module.exports = __toCommonJS(name);
229+
// Find and include the semicolon
230+
let statementEnd = toCommonJSEnd
231+
while (
232+
statementEnd < content.length &&
233+
(content[statementEnd] === ';' ||
234+
content[statementEnd] === ' ' ||
235+
content[statementEnd] === '\n')
236+
) {
237+
if (content[statementEnd] === ';') {
238+
statementEnd++
239+
break
240+
}
241+
statementEnd++
242+
}
243+
// Replace the entire statement with a comment
230244
s.overwrite(
231245
toCommonJSStart,
232-
toCommonJSEnd,
246+
statementEnd,
233247
'/* module.exports will be set at end of file */',
234248
)
235249

@@ -244,10 +258,18 @@ async function processDirectory(dir, verbose = false) {
244258
}
245259

246260
// Check if this is a single default export (legacy pattern)
261+
// Only match 'exports.default =' that is NOT preceded by 'module.'
247262
if (content.includes('exports.default =')) {
248263
// Transform exports.default = value to module.exports = value
249264
let pos = 0
250265
while ((pos = content.indexOf('exports.default = ', pos)) !== -1) {
266+
// Check if this is preceded by 'module.'
267+
const beforePos = pos - 'module.'.length
268+
if (beforePos >= 0 && content.slice(beforePos, pos) === 'module.') {
269+
// Skip module.exports.default (it's already correct)
270+
pos += 1
271+
continue
272+
}
251273
s.overwrite(
252274
pos,
253275
pos + 'exports.default = '.length,

0 commit comments

Comments
 (0)