From 89d6711cd97c66d63eb20e6aad72459a0324e7a7 Mon Sep 17 00:00:00 2001 From: patak Date: Wed, 1 Jun 2022 07:18:55 +0200 Subject: [PATCH] fix: SSR deep imports externalization (fixes #8420) (#8421) * fix: respect package.exports when resolving SSR deep imports * fix: don't externalize .css deep imports --- packages/vite/src/node/plugins/resolve.ts | 14 +++++++--- packages/vite/src/node/ssr/ssrExternal.ts | 32 ++++++++--------------- 2 files changed, 22 insertions(+), 24 deletions(-) diff --git a/packages/vite/src/node/plugins/resolve.ts b/packages/vite/src/node/plugins/resolve.ts index 538389828ed2c2..33a5ad31efe5b4 100644 --- a/packages/vite/src/node/plugins/resolve.ts +++ b/packages/vite/src/node/plugins/resolve.ts @@ -262,7 +262,6 @@ export function resolvePlugin(baseOptions: InternalResolveOptions): Plugin { // bare package imports, perform node resolve if (bareImportRE.test(id)) { const external = options.shouldExternalize?.(id) - if ( !external && asSrc && @@ -636,8 +635,17 @@ export function tryNodeResolve( return resolved } const resolvedExt = path.extname(resolved.id) - const resolvedId = - isDeepImport && path.extname(id) !== resolvedExt ? id + resolvedExt : id + let resolvedId = id + if (isDeepImport) { + // check ext before externalizing - only externalize + // extension-less imports and explicit .js imports + if (resolvedExt && !resolved.id.match(/(.js|.mjs|.cjs)$/)) { + return + } + if (!pkg?.data.exports && path.extname(id) !== resolvedExt) { + resolvedId += resolvedExt + } + } return { ...resolved, id: resolvedId, external: true } } diff --git a/packages/vite/src/node/ssr/ssrExternal.ts b/packages/vite/src/node/ssr/ssrExternal.ts index 512ec038a21244..fbba0e735f7df1 100644 --- a/packages/vite/src/node/ssr/ssrExternal.ts +++ b/packages/vite/src/node/ssr/ssrExternal.ts @@ -139,29 +139,19 @@ function createIsSsrExternal( isBuild: true } - const isPackageEntry = (id: string) => { + const isValidPackageEntry = (id: string) => { if (!bareImportRE.test(id) || id.includes('\0')) { return false } - if ( - tryNodeResolve( - id, - undefined, - resolveOptions, - ssr?.target === 'webworker', - undefined, - true - ) - ) { - return true - } - try { - // no main entry, but deep imports may be allowed - if (resolveFrom(`${id}/package.json`, root)) { - return true - } - } catch {} - return false + return !!tryNodeResolve( + id, + undefined, + resolveOptions, + ssr?.target === 'webworker', + undefined, + true, + true // try to externalize, will return undefined if not possible + ) } return (id: string) => { @@ -171,7 +161,7 @@ function createIsSsrExternal( const external = !id.startsWith('.') && !path.isAbsolute(id) && - (isBuiltin(id) || (isConfiguredAsExternal(id) && isPackageEntry(id))) + (isBuiltin(id) || (isConfiguredAsExternal(id) && isValidPackageEntry(id))) processedIds.set(id, external) return external }