module: fix extensionless entry with explicit type=commonjs

PR-URL: https://github.com/nodejs/node/pull/61600
Fixes: https://github.com/nodejs/node/issues/61104
Reviewed-By: Joyee Cheung <joyeec9h3@gmail.com>
Reviewed-By: Marco Ippolito <marcoippolito54@gmail.com>
Reviewed-By: Stephen Belanger <admin@stephenbelanger.com>
This commit is contained in:
Yuya Inoue authored and Antoine du Hamel committed 2026-02-19 11:14:04 +01:00
1 parent 435f3dd8e4
commit 24b858547a
6 files changed
+42

No files matched your search

+9
View File
@@ -1931,6 +1931,15 @@ Module._extensions['.js'] = function(module, filename) {
} else {
format = 'typescript';
}
} else if (path.extname(filename) === '') {
// Extensionless files skip the .js suffix check above. When type is explicit,
// follow it so ESM syntax surfaces as SyntaxError for commonjs instead of
// silently delegating to ESM.
pkg = packageJsonReader.getNearestParentPackageJSON(filename);
const typeFromPjson = pkg?.data?.type;
if (typeFromPjson === 'commonjs' || typeFromPjson === 'module') {
format = typeFromPjson;
}
}
const { source, format: loadedFormat } = loadSource(module, filename, format);
// Function require shouldn't be used in ES modules when require(esm) is disabled.
@@ -0,0 +1,19 @@
'use strict';
require('../common');
const { spawnSyncAndAssert } = require('../common/child_process');
const fixtures = require('../common/fixtures');
spawnSyncAndAssert(process.execPath, [
fixtures.path('es-modules', 'extensionless-esm-commonjs', 'script'),
], {
status: 1,
stderr: /SyntaxError: Cannot use import statement outside a module/,
});
spawnSyncAndAssert(process.execPath, [
fixtures.path('es-modules', 'extensionless-esm-module', 'script'),
], {
stdout: /script STARTED[\s\S]*v\d+\./,
trim: true,
});
@@ -0,0 +1,3 @@
{
"type": "commonjs"
}
+4
View File
@@ -0,0 +1,4 @@
#!/usr/bin/env node
console.log('script STARTED')
import { version } from 'node:process'
console.log(version)
@@ -0,0 +1,3 @@
{
"type": "module"
}
+4
View File
@@ -0,0 +1,4 @@
#!/usr/bin/env node
console.log('script STARTED')
import { version } from 'node:process'
console.log(version)