Skip to content

Commit e171a5d

Browse files
committed
Fixes #5411.
Fail with an informative error message on a file with a broken default import.
1 parent a908b3b commit e171a5d

File tree

4 files changed

+36
-8
lines changed

4 files changed

+36
-8
lines changed

lib/nodejs/esm-utils.js

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -93,8 +93,15 @@ const requireModule = async (file, esmDecorator) => {
9393
try {
9494
return require(file);
9595
} catch (err) {
96-
// Import if require fails.
97-
return dealWithExports(await formattedImport(file, esmDecorator));
96+
if (
97+
err instanceof SyntaxError &&
98+
err.message.includes("does not provide an export named 'default'")
99+
) {
100+
throw err;
101+
} else {
102+
// Import if require fails.
103+
return dealWithExports(await formattedImport(file, esmDecorator));
104+
}
98105
}
99106
}
100107

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

Lines changed: 23 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5,15 +5,32 @@ const sinon = require('sinon');
55
const url = require('node:url');
66

77
describe('esm-utils', function () {
8-
beforeEach(function () {
9-
sinon.stub(esmUtils, 'doImport').resolves({});
10-
});
11-
12-
afterEach(function () {
13-
sinon.restore();
8+
describe('requireOrImport', function () {
9+
it('should show an informative error message for a broken default import', async function () {
10+
return expect(
11+
() =>
12+
esmUtils.requireOrImport(
13+
'../../test/node-unit/fixtures/broken-default-import.mjs'
14+
),
15+
'to be rejected with error satisfying',
16+
{
17+
name: 'SyntaxError',
18+
message:
19+
"The requested module './module-without-default-export.mjs' does not provide an export named 'default'"
20+
}
21+
);
22+
});
1423
});
1524

1625
describe('loadFilesAsync()', function () {
26+
beforeEach(function () {
27+
sinon.stub(esmUtils, 'doImport').resolves({});
28+
});
29+
30+
afterEach(function () {
31+
sinon.restore();
32+
});
33+
1734
it('should not decorate imported module if no decorator passed', async function () {
1835
await esmUtils.loadFilesAsync(
1936
['/foo/bar.mjs'],
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
import moduleWithoutDefaultExport from './module-without-default-export.mjs';
2+
3+
moduleWithoutDefaultExport;
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
export const value = 42;

0 commit comments

Comments
 (0)