Skip to content

Commit 9cda6cf

Browse files
committed
module: fix error reporting when commonjs requires an ES module
1 parent 03ec900 commit 9cda6cf

File tree

5 files changed

+46
-0
lines changed

5 files changed

+46
-0
lines changed

lib/internal/modules/cjs/loader.js

+2
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@ const {
3636
ArrayPrototypeUnshiftApply,
3737
Boolean,
3838
Error,
39+
ErrorCaptureStackTrace,
3940
JSONParse,
4041
ObjectDefineProperty,
4142
ObjectFreeze,
@@ -1674,6 +1675,7 @@ function getRequireESMError(mod, pkg, content, filename) {
16741675
const usesEsm = containsModuleSyntax(content, filename);
16751676
const err = new ERR_REQUIRE_ESM(filename, usesEsm, parentPath,
16761677
packageJsonPath);
1678+
ErrorCaptureStackTrace(err, Module.prototype.require);
16771679
// Attempt to reconstruct the parent require frame.
16781680
const parentModule = Module._cache[parentPath];
16791681
if (parentModule) {
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
import nothing from 'somewhere';
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
function main() {
2+
func1(func2(func3()))
3+
}
4+
5+
function func1() {
6+
require('./app.js')
7+
}
8+
function func2() {}
9+
function func3() {}
10+
11+
main()
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
{
2+
"type": "module"
3+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
import '../common/index.mjs';
2+
import { test } from 'node:test';
3+
import * as fixtures from '../common/fixtures.mjs';
4+
import { spawnSync } from 'node:child_process';
5+
import assert from 'node:assert';
6+
import { EOL } from 'node:os';
7+
8+
test('correctly reports error for a longer stack trace', () => {
9+
// The following regex matches the error message that is expected to be thrown
10+
//
11+
// package-type-module/require-esm-error-annotation/longer-stack.cjs:6
12+
// require('./app.js')
13+
// ^
14+
15+
const fixture = fixtures.path('es-modules/package-type-module/require-esm-error-annotation/index.cjs');
16+
const args = ['--no-experimental-require-module', fixture];
17+
18+
const lineNumber = 6;
19+
const lineContent = "require('./app.js')";
20+
const fullMessage = `${fixture}:${lineNumber}${EOL} ${lineContent}${EOL} ^${EOL}`;
21+
22+
const result = spawnSync(process.execPath, args);
23+
24+
console.log(`STDERR: ${result.stderr.toString()}`);
25+
26+
assert.strictEqual(result.status, 1);
27+
assert.strictEqual(result.stdout.toString(), '');
28+
assert(result.stderr.toString().indexOf(fullMessage) > -1);
29+
});

0 commit comments

Comments
 (0)