Skip to content

Commit

Permalink
ESM: fix swallowing MODULE_NOT_FOUND errors in case of type:module (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
giltayar authored Jul 13, 2021
1 parent 5c59da0 commit 6830821
Show file tree
Hide file tree
Showing 4 changed files with 39 additions and 4 deletions.
16 changes: 15 additions & 1 deletion lib/esm-utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,21 @@ exports.requireOrImport = hasStableEsmImplementation
err.code === 'ERR_UNKNOWN_FILE_EXTENSION' ||
err.code === 'ERR_UNSUPPORTED_DIR_IMPORT'
) {
return require(file);
try {
return require(file);
} catch (requireErr) {
if (requireErr.code === 'ERR_REQUIRE_ESM') {
// This happens when the test file is a JS file, but via type:module is actually ESM,
// AND has an import to a file that doesn't exist.
// This throws an `ERR_MODULE_NOT_FOUND` // error above,
// and when we try to `require` it here, it throws an `ERR_REQUIRE_ESM`.
// What we want to do is throw the original error (the `ERR_MODULE_NOT_FOUND`),
// and not the `ERR_REQUIRE_ESM` error, which is a red herring.
throw err;
} else {
throw requireErr;
}
}
} else {
throw err;
}
Expand Down
18 changes: 15 additions & 3 deletions test/integration/esm.spec.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
'use strict';
var path = require('path');
var helpers = require('./helpers');
var run = helpers.runMochaJSON;
var runMochaAsync = helpers.runMochaAsync;
const {runMochaJSON: run, runMochaAsync} = require('./helpers');
var utils = require('../../lib/utils');
var args =
+process.versions.node.split('.')[0] >= 13 ? [] : ['--experimental-modules'];
Expand Down Expand Up @@ -81,4 +79,18 @@ describe('esm', function() {

expect(result, 'to have passed test count', 1);
});

it('should throw an ERR_MODULE_NOT_FOUND and not ERR_REQUIRE_ESM if file imports a non-existing module', async function() {
const fixture =
'esm/type-module/test-that-imports-non-existing-module.fixture.js';

const err = await runMochaAsync(fixture, ['--unhandled-rejections=warn'], {
stdio: 'pipe'
}).catch(err => err);

expect(err.output, 'to contain', 'ERR_MODULE_NOT_FOUND').and(
'to contain',
'test-that-imports-non-existing-module'
);
});
});
3 changes: 3 additions & 0 deletions test/integration/fixtures/esm/type-module/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"type": "module"
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import assert from 'assert';
import './this-module-does-not-exist.js';

it('should not pass (or even run) because above import will fail', () => {
assert(true);
});

0 comments on commit 6830821

Please sign in to comment.