Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 5 additions & 4 deletions lib/internal/modules/cjs/loader.js
Original file line number Diff line number Diff line change
Expand Up @@ -1932,12 +1932,13 @@ Module._extensions['.js'] = function(module, filename) {
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.
// Extensionless files skip the .js suffix check above. When type is commonjs,
// follow it so ESM syntax surfaces as SyntaxError instead of silently
// delegating to ESM. For type: module, leave format undefined so our syntax
// detection handles it (allowing CJS extensionless files in ESM packages).
pkg = packageJsonReader.getNearestParentPackageJSON(filename);
const typeFromPjson = pkg?.data?.type;
if (typeFromPjson === 'commonjs' || typeFromPjson === 'module') {
if (typeFromPjson === 'commonjs') {
format = typeFromPjson;
}
}
Expand Down
10 changes: 10 additions & 0 deletions test/es-module/test-extensionless-esm-type-commonjs.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,13 @@ spawnSyncAndAssert(process.execPath, [
stdout: /script STARTED[\s\S]*v\d+\./,
trim: true,
});

// CJS extensionless file inside a type: "module" package should work
// when require()'d. Regression test for https://github.com/nodejs/node/issues/61971
spawnSyncAndAssert(process.execPath, [
'-e', `const m = require(${JSON.stringify(
fixtures.path('es-modules', 'extensionless-cjs-module', 'index')
)}); if (m.hello !== 'world') throw new Error('expected CJS exports, got: ' + JSON.stringify(m))`,
], {
status: 0,
});
1 change: 1 addition & 0 deletions test/fixtures/es-modules/extensionless-cjs-module/index
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
module.exports = { hello: 'world' };
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"type": "module"
}
Loading