Skip to content

Commit ebdbc48

Browse files
fix: use original require() error for TS files if ERR_UNKNOWN_FILE_EXTENSION (#5408)
* fix: use original require() error if ERR_UNKNOWN_FILE_EXTENSION * Update lib/nodejs/esm-utils.js Co-authored-by: Mark Wiemer <[email protected]> * Add in comments * test: add broken-syntax.ts fixture and test * chore: reset a change to main * test: slightly improve name --------- Co-authored-by: Mark Wiemer <[email protected]>
1 parent 4122c7d commit ebdbc48

File tree

3 files changed

+31
-0
lines changed

3 files changed

+31
-0
lines changed

lib/nodejs/esm-utils.js

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -101,9 +101,24 @@ const requireModule = async (file, esmDecorator) => {
101101
try {
102102
return dealWithExports(await formattedImport(file, esmDecorator));
103103
} catch (importErr) {
104+
// If a --require module throws in a Node.js version that doesn't yet support .ts files,
105+
// the fallback import() will throw an uninformative error about the file extension.
106+
// What we actually care about is the original require() error.
107+
// See: https://github.com/mochajs/mocha/issues/5393
108+
if (
109+
/\.(cts|mts|ts)$/.test(file) ||
110+
importErr.code === 'ERR_UNKNOWN_FILE_EXTENSION'
111+
) {
112+
throw requireErr;
113+
}
114+
115+
// Similarly, for an exports/imports mismatch such as a missing 'default',
116+
// the require() error will be more informative for users.
117+
// See: https://github.com/mochajs/mocha/issues/5411
104118
if (importErr.code === 'ERR_INTERNAL_ASSERTION') {
105119
throw requireErr;
106120
}
121+
107122
throw importErr;
108123
}
109124
}

test/node-unit/esm-utils.spec.js

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,21 @@ describe('esm-utils', function () {
2020
}
2121
);
2222
});
23+
24+
it('should show a syntax error message when importing a TypeScript file with invalid syntax', async function () {
25+
return expect(
26+
() =>
27+
esmUtils.requireOrImport(
28+
'../../test/node-unit/fixtures/broken-syntax.ts'
29+
),
30+
'to be rejected with error satisfying',
31+
{
32+
name: 'SyntaxError',
33+
message:
34+
/Invalid or unexpected token|Expected ident/
35+
}
36+
);
37+
});
2338
});
2439

2540
describe('loadFilesAsync()', function () {
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
@!

0 commit comments

Comments
 (0)