From c1a83e4e2d58b8e96b9e81162e1b5666ebbc8711 Mon Sep 17 00:00:00 2001 From: Anton Evzhakov Date: Tue, 6 Feb 2024 12:41:39 +0200 Subject: [PATCH] fix(shared): crash while resolving esm-only package (#49) * fix(shared): crash while resolving esm-only package * chore: changeset --- .changeset/empty-poets-kick.md | 5 +++++ packages/shared/src/findPackageJSON.ts | 21 ++++++++++++++++----- 2 files changed, 21 insertions(+), 5 deletions(-) create mode 100644 .changeset/empty-poets-kick.md diff --git a/.changeset/empty-poets-kick.md b/.changeset/empty-poets-kick.md new file mode 100644 index 00000000..da276e3b --- /dev/null +++ b/.changeset/empty-poets-kick.md @@ -0,0 +1,5 @@ +--- +'@wyw-in-js/shared': patch +--- + +Fix crash while resolving esm-only package. Fixes #43 diff --git a/packages/shared/src/findPackageJSON.ts b/packages/shared/src/findPackageJSON.ts index 5db6387d..567444a6 100644 --- a/packages/shared/src/findPackageJSON.ts +++ b/packages/shared/src/findPackageJSON.ts @@ -27,11 +27,12 @@ export function findPackageJSON( return cache.get(pkgPath); } catch (er: unknown) { - if ( - typeof er === 'object' && - er !== null && - (er as { code?: unknown }).code === 'MODULE_NOT_FOUND' - ) { + const code = + typeof er === 'object' && er !== null && 'code' in er + ? er.code + : undefined; + + if (code === 'MODULE_NOT_FOUND') { if (skipPathsOptions && filename) { return findPackageJSON(pkgName, null); } @@ -39,6 +40,16 @@ export function findPackageJSON( return undefined; } + if (code === 'ERR_PACKAGE_PATH_NOT_EXPORTED') { + // See https://github.com/Anber/wyw-in-js/issues/43 + // `require` can't resolve ESM-only packages. We can use the `resolve` + // package here, but it does not solve all cases because `pkgName` + // can be an alias and should be resolved by a bundler. However, we can't use + // `resolve` from a bundler because it is async. The good news is that in that + // specific case, we can just ignore those packages. For now. + return undefined; + } + throw er; } }