Skip to content

Commit

Permalink
fix: SSR deep imports externalization (fixes #8420) (#8421)
Browse files Browse the repository at this point in the history
* fix: respect package.exports when resolving SSR deep imports
* fix: don't externalize .css deep imports
  • Loading branch information
patak-dev authored Jun 1, 2022
1 parent ab23e6e commit 89d6711
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 24 deletions.
14 changes: 11 additions & 3 deletions packages/vite/src/node/plugins/resolve.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 &&
Expand Down Expand Up @@ -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 }
}

Expand Down
32 changes: 11 additions & 21 deletions packages/vite/src/node/ssr/ssrExternal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) => {
Expand All @@ -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
}
Expand Down

0 comments on commit 89d6711

Please sign in to comment.