Skip to content

Commit a68344f

Browse files
fix: show require() error on unsupported directory import (#6354)
1 parent d59467a commit a68344f

2 files changed

Lines changed: 34 additions & 0 deletions

File tree

‎lib/nodejs/esm-utils.cjs‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -116,6 +116,13 @@ const requireModule = async (file, esmDecorator) => {
116116
throw requireErr;
117117
}
118118

119+
// A directory specifier resolves under CommonJS but not under ESM so this error
120+
// only means the fallback import() never got far enough to say anything useful about the file.
121+
// Check this issue https://github.com/mochajs/mocha/issues/5792
122+
if (importErr.code === "ERR_UNSUPPORTED_DIR_IMPORT") {
123+
throw requireErr;
124+
}
125+
119126
// Similarly, for an exports/imports mismatch such as a missing 'default',
120127
// the require() error will be more informative for users.
121128
// See: https://github.com/mochajs/mocha/issues/5411

‎test/node-unit/esm-utils.spec.cjs‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,10 @@ const url = require("node:url");
66

77
describe("esm-utils", function () {
88
describe("requireOrImport", function () {
9+
afterEach(function () {
10+
sinon.restore();
11+
});
12+
913
it("should show an informative error message for a broken default import", async function () {
1014
return expect(
1115
() =>
@@ -62,6 +66,29 @@ describe("esm-utils", function () {
6266
},
6367
);
6468
});
69+
70+
it("should surface the require() error when import() fails on a directory specifier", async function () {
71+
sinon
72+
.stub(esmUtils, "doImport")
73+
.rejects(
74+
Object.assign(
75+
new Error("Directory import '/fixtures/lib' is not supported"),
76+
{ code: "ERR_UNSUPPORTED_DIR_IMPORT" },
77+
),
78+
);
79+
80+
return expect(
81+
() =>
82+
esmUtils.requireOrImport(
83+
"../../test/node-unit/fixtures/this-module-does-not-exist.cjs",
84+
),
85+
"to be rejected with error satisfying",
86+
{
87+
code: "MODULE_NOT_FOUND",
88+
message: /this-module-does-not-exist/,
89+
},
90+
);
91+
});
6592
});
6693

6794
describe("loadFilesAsync()", function () {

0 commit comments

Comments
 (0)