From 60e18e95b366c845501fc30f5e607ab5bf9d2035 Mon Sep 17 00:00:00 2001 From: Ben Newman Date: Wed, 23 Jun 2021 12:02:56 -0400 Subject: [PATCH] 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). --- config/resolveModuleIds.ts | 30 +++++++++++++++++++++++++++--- 1 file changed, 27 insertions(+), 3 deletions(-) diff --git a/config/resolveModuleIds.ts b/config/resolveModuleIds.ts index 061fd7a4826..37dec13b646 100644 --- a/config/resolveModuleIds.ts +++ b/config/resolveModuleIds.ts @@ -54,20 +54,44 @@ function isRelative(id: string) { } function normalizeSourceString(file: string, source?: Node | null) { - if (source && n.StringLiteral.check(source) && isRelative(source.value)) { + if (source && n.StringLiteral.check(source)) { try { - source.value = normalizeId(source.value, file); + source.value = isRelative(source.value) + ? normalizeId(source.value, file) + : normalizeNonRelativeId(source.value, file); } catch (error) { - console.error(`Failed to resolve ${source.value} in ${file}`); + console.error(`Failed to resolve ${source.value} in ${file} with error ${error}`); process.exit(1); } } } +function normalizeNonRelativeId(id: string, file: string) { + const normal = normalizeId(id, file); + const normalParts = normal.split("/"); + const sourceParts = id.split("/"); + const nodeModulesIndex = normalParts.lastIndexOf("node_modules"); + if ( + nodeModulesIndex >= 0 && + normalParts[nodeModulesIndex + 1] === sourceParts[0] + ) { + const bareModuleIdentifier = + normalParts.slice(nodeModulesIndex + 1).join("/"); + if (normal === normalizeId(bareModuleIdentifier, file)) { + return bareModuleIdentifier; + } + console.error(`Leaving ${id} import in ${file} unchanged because ${ + bareModuleIdentifier + } does not resolve to the same module`); + } + return id; +} + function normalizeId(id: string, file: string) { const basedir = path.dirname(file); const absPath = resolve.sync(id, { basedir, + extensions: [".mjs", ".js"], packageFilter(pkg) { return pkg.module ? { ...pkg,