Skip to content

Commit

Permalink
fix: fallback to browser field without postfix
Browse files Browse the repository at this point in the history
  • Loading branch information
sapphi-red committed Mar 4, 2022
1 parent 5169c27 commit fe040cd
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 5 deletions.
3 changes: 2 additions & 1 deletion packages/playground/resolve/browser-field/package.json
Expand Up @@ -12,6 +12,7 @@
"./no-ext-index": "./out/esm.browser.js",
"./not-browser.js": false,
"./multiple.dot.path.js": false,
"jsdom": false
"jsdom": false,
"./question.js?query": "./out/esm.browser.js"
}
}
4 changes: 3 additions & 1 deletion packages/playground/resolve/index.html
Expand Up @@ -158,10 +158,12 @@ <h2>resolve package that contains # in path</h2>
import e from 'resolve-browser-field/ext-index/index.js'
import f from 'resolve-browser-field/ext-index'
import g from 'resolve-browser-field/no-ext-index/index.js' // no substitution
import h from 'resolve-browser-field/question.js?query'
import i from 'resolve-browser-field/no-ext?query'

import { ra, rb, rc, rd, re, rf, rg } from 'resolve-browser-field/relative'

const success = [main, a, c, d, e, f, ra, rc, rd, re, rf]
const success = [main, a, c, d, e, f, h, i, ra, rc, rd, re, rf]
const noSuccess = [b, g, rb, rg]

if (
Expand Down
31 changes: 28 additions & 3 deletions packages/vite/src/node/plugins/resolve.ts
Expand Up @@ -917,12 +917,37 @@ function mapWithBrowserField(
): string | false | undefined {
const normalizedPath = path.posix.normalize(relativePathInPkgDir)

const result = _mapWithBrowserField(normalizedPath, map)
if (result !== undefined) {
return result
}

// try without postfix for `import 'something/path.js?query'` (see #7098)
const { file: normalizedPathWithoutPostfix, postfix } =
splitFileAndPostfix(normalizedPath)
if (!postfix) {
return undefined
}
const resultWithoutPostfix = _mapWithBrowserField(
normalizedPathWithoutPostfix,
map
)
if (typeof resultWithoutPostfix === 'string') {
return resultWithoutPostfix + postfix
}
return resultWithoutPostfix
}

function _mapWithBrowserField(
normalizedRelativePath: string,
map: Record<string, string | false>
): string | false | undefined {
for (const key in map) {
const normalizedKey = path.posix.normalize(key)
if (
normalizedPath === normalizedKey ||
equalWithoutSuffix(normalizedPath, normalizedKey, '.js') ||
equalWithoutSuffix(normalizedPath, normalizedKey, '/index.js')
normalizedRelativePath === normalizedKey ||
equalWithoutSuffix(normalizedRelativePath, normalizedKey, '.js') ||
equalWithoutSuffix(normalizedRelativePath, normalizedKey, '/index.js')
) {
return map[key]
}
Expand Down

0 comments on commit fe040cd

Please sign in to comment.