Skip to content

Commit f6e5bda

Browse files
committed
Make resolveModuleIds.ts resolve bare/non-relative package imports, too.
For example, this rewrites the import from "ts-invariant/process" in @apollo/client/utilities/globals/graphql.js to instead import from "ts-invariant/process/index.js, so Node.js won't complain about the directory import (even though ts-invariant/process/package.json exists).
1 parent 020c5e1 commit f6e5bda

File tree

1 file changed

+26
-3
lines changed

1 file changed

+26
-3
lines changed

config/resolveModuleIds.ts

Lines changed: 26 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -54,16 +54,39 @@ function isRelative(id: string) {
5454
}
5555

5656
function normalizeSourceString(file: string, source?: Node | null) {
57-
if (source && n.StringLiteral.check(source) && isRelative(source.value)) {
57+
if (source && n.StringLiteral.check(source)) {
5858
try {
59-
source.value = normalizeId(source.value, file);
59+
source.value = isRelative(source.value)
60+
? normalizeId(source.value, file)
61+
: normalizeNonRelativeId(source.value, file);
6062
} catch (error) {
61-
console.error(`Failed to resolve ${source.value} in ${file}`);
63+
console.error(`Failed to resolve ${source.value} in ${file} with error ${error}`);
6264
process.exit(1);
6365
}
6466
}
6567
}
6668

69+
function normalizeNonRelativeId(id: string, file: string) {
70+
const normal = normalizeId(id, file);
71+
const normalParts = normal.split("/");
72+
const sourceParts = id.split("/");
73+
const nodeModulesIndex = normalParts.lastIndexOf("node_modules");
74+
if (
75+
nodeModulesIndex >= 0 &&
76+
normalParts[nodeModulesIndex + 1] === sourceParts[0]
77+
) {
78+
const bareModuleIdentifier =
79+
normalParts.slice(nodeModulesIndex + 1).join("/");
80+
if (normal === normalizeId(bareModuleIdentifier, file)) {
81+
return bareModuleIdentifier;
82+
}
83+
console.error(`Leaving ${id} import in ${file} unchanged because ${
84+
bareModuleIdentifier
85+
} does not resolve to the same module`);
86+
}
87+
return id;
88+
}
89+
6790
function normalizeId(id: string, file: string) {
6891
const basedir = path.dirname(file);
6992
const absPath = resolve.sync(id, {

0 commit comments

Comments
 (0)