Skip to content

Commit 24b8585

Browse files
inoway46aduh95
authored andcommitted
module: fix extensionless entry with explicit type=commonjs
PR-URL: #61600 Fixes: #61104 Reviewed-By: Joyee Cheung <joyeec9h3@gmail.com> Reviewed-By: Marco Ippolito <marcoippolito54@gmail.com> Reviewed-By: Stephen Belanger <admin@stephenbelanger.com>
1 parent 435f3dd commit 24b8585

File tree

6 files changed

+42
-0
lines changed

6 files changed

+42
-0
lines changed

β€Žlib/internal/modules/cjs/loader.jsβ€Ž

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1931,6 +1931,15 @@ Module._extensions['.js'] = function(module, filename) {
19311931
} else {
19321932
format = 'typescript';
19331933
}
1934+
} else if (path.extname(filename) === '') {
1935+
// Extensionless files skip the .js suffix check above. When type is explicit,
1936+
// follow it so ESM syntax surfaces as SyntaxError for commonjs instead of
1937+
// silently delegating to ESM.
1938+
pkg = packageJsonReader.getNearestParentPackageJSON(filename);
1939+
const typeFromPjson = pkg?.data?.type;
1940+
if (typeFromPjson === 'commonjs' || typeFromPjson === 'module') {
1941+
format = typeFromPjson;
1942+
}
19341943
}
19351944
const { source, format: loadedFormat } = loadSource(module, filename, format);
19361945
// Function require shouldn't be used in ES modules when require(esm) is disabled.
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
'use strict';
2+
3+
require('../common');
4+
const { spawnSyncAndAssert } = require('../common/child_process');
5+
const fixtures = require('../common/fixtures');
6+
7+
spawnSyncAndAssert(process.execPath, [
8+
fixtures.path('es-modules', 'extensionless-esm-commonjs', 'script'),
9+
], {
10+
status: 1,
11+
stderr: /SyntaxError: Cannot use import statement outside a module/,
12+
});
13+
14+
spawnSyncAndAssert(process.execPath, [
15+
fixtures.path('es-modules', 'extensionless-esm-module', 'script'),
16+
], {
17+
stdout: /script STARTED[\s\S]*v\d+\./,
18+
trim: true,
19+
});
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
{
2+
"type": "commonjs"
3+
}
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
#!/usr/bin/env node
2+
console.log('script STARTED')
3+
import { version } from 'node:process'
4+
console.log(version)
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
{
2+
"type": "module"
3+
}
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
#!/usr/bin/env node
2+
console.log('script STARTED')
3+
import { version } from 'node:process'
4+
console.log(version)

0 commit comments

Comments
Β (0)