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
5 changes: 5 additions & 0 deletions lib/internal/modules/cjs/loader.js
Original file line number Diff line number Diff line change
Expand Up @@ -1652,6 +1652,11 @@ function finalizeEsmResolution(resolved, parentPath, pkgPath) {
throw new ERR_INVALID_MODULE_SPECIFIER(
resolved, 'must not include encoded "/" or "\\" characters', parentPath);
}
// A package import may resolve to a builtin module, which is represented
// as a node: URL and has no file path to resolve.
if (resolved.protocol === 'node:') {
return BuiltinModule.normalizeRequirableId(resolved.href);
}
const filename = fileURLToPath(resolved);
const actual = tryFile(filename);
if (actual) {
Expand Down
10 changes: 10 additions & 0 deletions test/es-module/test-esm-imports.mjs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { mustCall } from '../common/index.mjs';
import assert from 'assert';
import path from 'node:path';

import importer from '../fixtures/es-modules/pkgimports/importer.js';
import { requireFixture } from '../fixtures/pkgexports.mjs';
Expand Down Expand Up @@ -122,6 +123,15 @@ const { requireImport, importImport } = importer;
}
});

// Package imports can resolve to a builtin module. The CJS loader must load
// the resolved node: URL as a builtin instead of converting it to a file path.
requireImport('#builtin').then(mustCall(({ default: actual }) => {
assert.strictEqual(actual, path);
}));
importImport('#builtin').then(mustCall((actual) => {
assert.strictEqual(actual.default, path);
}));

// CJS resolver must still support #package packages in node_modules
requireFixture('#cjs').then(mustCall((actual) => {
assert.strictEqual(actual.default, 'cjs backcompat');
Expand Down
1 change: 1 addition & 0 deletions test/fixtures/es-modules/pkgimports/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
"#subpath/null": null,
"#subpath/*.asdf": "./test.js",
"#external": "pkgexports/valid-cjs",
"#builtin": "path",
"#external/subpath/*": "pkgexports/sub/*",
"#external/invalidsubpath/": "pkgexports/sub",
"#belowbase": "../belowbase",
Expand Down