Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 7 additions & 54 deletions packages/vite/src/node/plugins/resolve.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import colors from 'picocolors'
import type { PartialResolvedId } from 'rolldown'
import { viteResolvePlugin } from 'rolldown/experimental'
import { exports, imports } from 'resolve.exports'
import { hasESMSyntax } from 'mlly'
import type { Plugin } from '../plugin'
import {
CLIENT_ENTRY,
Expand Down Expand Up @@ -932,14 +931,15 @@ export function resolvePackageEntry(
// fallback to mainFields if still not resolved
if (!entryPoint) {
for (const field of options.mainFields) {
if (field === 'browser') {
entryPoint = tryResolveBrowserEntry(dir, data, options)
if (entryPoint) {
break
}
} else if (typeof data[field] === 'string') {
if (typeof data[field] === 'string') {
entryPoint = data[field]
break
} else if (field === 'browser') {
const browser = data[field]
if (isObject(browser) && browser['.']) {
entryPoint = browser['.']
break
}
}
}
}
Expand Down Expand Up @@ -1109,53 +1109,6 @@ function resolveDeepImport(
}
}

function tryResolveBrowserEntry(
dir: string,
data: PackageData['data'],
options: InternalResolveOptions,
) {
// handle edge case with browser and module field semantics

// check browser field
// https://github.com/defunctzombie/package-browser-field-spec
const browserEntry =
typeof data.browser === 'string'
? data.browser
: isObject(data.browser) && data.browser['.']
if (browserEntry) {
// check if the package also has a "module" field.
if (
!options.isRequire &&
options.mainFields.includes('module') &&
typeof data.module === 'string' &&
data.module !== browserEntry
) {
// if both are present, we may have a problem: some package points both
// to ESM, with "module" targeting Node.js, while some packages points
// "module" to browser ESM and "browser" to UMD/IIFE.
// the heuristics here is to actually read the browser entry when
// possible and check for hints of ESM. If it is not ESM, prefer "module"
// instead; Otherwise, assume it's ESM and use it.
const resolvedBrowserEntry = tryFsResolve(
path.join(dir, browserEntry),
options,
)
if (resolvedBrowserEntry) {
const content = fs.readFileSync(resolvedBrowserEntry, 'utf-8')
if (hasESMSyntax(content)) {
// likely ESM, prefer browser
return browserEntry
} else {
// non-ESM, UMD or IIFE or CJS(!!! e.g. firebase 7.x), prefer module
return data.module
}
}
} else {
return browserEntry
}
}
}

/**
* given a relative path in pkg dir,
* return a relative path in pkg dir,
Expand Down