Skip to content

Commit 0d86b34

Browse files
bteasapphi-red
andauthored
fix(resolve): support subpath imports with multiple # (#23631)
Co-authored-by: sapphi-red <[email protected]>
1 parent 6a02780 commit 0d86b34

11 files changed

Lines changed: 155 additions & 11 deletions

File tree

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
{
2+
"name": "resolve-subpath-imports",
3+
"imports": {
4+
"#hash": "./public.js",
5+
"#hash#blocked": null,
6+
"#hash?blocked": null
7+
}
8+
}

‎packages/vite/src/node/__tests__/resolve.spec.ts‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,27 @@ import { join } from 'node:path'
22
import { describe, expect, onTestFinished, test, vi } from 'vitest'
33
import { build } from '../build'
44
import type { EnvironmentOptions, InlineConfig } from '../config'
5+
import { resolveSubpathImports } from '../plugins/resolve'
56
import { createServer } from '../server'
67
import { createServerModuleRunner } from '../ssr/runtime/serverModuleRunner'
78

9+
for (const id of ['#hash#blocked', '#hash?blocked']) {
10+
test(`does not fall back from explicitly blocked imports key ${id}`, () => {
11+
expect(() =>
12+
resolveSubpathImports(
13+
id,
14+
join(import.meta.dirname, 'fixtures/resolve-subpath-imports/index.js'),
15+
{
16+
conditions: [],
17+
externalConditions: [],
18+
isProduction: false,
19+
isRequire: false,
20+
},
21+
),
22+
).toThrow(`Missing "${id}" specifier`)
23+
})
24+
}
25+
826
describe('import and resolveId', () => {
927
async function createTestServer() {
1028
const server = await createServer({

‎packages/vite/src/node/plugins/resolve.ts‎

Lines changed: 35 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -501,16 +501,41 @@ export function resolveSubpathImports(
501501
const basedir = path.dirname(importer)
502502
const pkgData = findNearestPackageData(basedir, options.packageCache)
503503
if (!pkgData) return
504-
505-
let { file: idWithoutPostfix, postfix } = splitFileAndPostfix(id.slice(1))
506-
idWithoutPostfix = '#' + idWithoutPostfix
507-
508-
let importsPath = resolveExportsOrImports(
509-
pkgData.data,
510-
idWithoutPostfix,
511-
options,
512-
'imports',
513-
)
504+
// Imports keys may themselves contain `#` or `?` (e.g. `##/*`, `#a?b`).
505+
// Try the full id first, then each query or hash boundary from right to left
506+
// so that the longest matching key wins (#16085, #23622).
507+
let importsPath: string | undefined
508+
let postfix = ''
509+
let fullIdError: unknown
510+
for (
511+
let postfixIndex = id.length;
512+
postfixIndex > 0;
513+
postfixIndex = Math.max(
514+
id.lastIndexOf('?', postfixIndex - 1),
515+
id.lastIndexOf('#', postfixIndex - 1),
516+
)
517+
) {
518+
const key = id.slice(0, postfixIndex)
519+
try {
520+
importsPath = resolveExportsOrImports(
521+
pkgData.data,
522+
key,
523+
options,
524+
'imports',
525+
)
526+
if (importsPath !== undefined) {
527+
postfix = id.slice(postfixIndex)
528+
break
529+
}
530+
} catch (e) {
531+
if (Object.hasOwn(pkgData.data.imports, key)) throw e
532+
// resolve.exports throws when no key matches; keep the full id error.
533+
fullIdError ??= e
534+
}
535+
}
536+
if (importsPath === undefined && fullIdError) {
537+
throw fullIdError
538+
}
514539

515540
if (importsPath?.[0] === '.') {
516541
importsPath = path.relative(basedir, path.join(pkgData.dir, importsPath))

‎playground/resolve/__tests__/resolve.spec.ts‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -249,6 +249,46 @@ test('Resolving #/ root alias pattern with imports field', async () => {
249249
expect(await page.textContent('.imports-root-slash')).toMatch('[success]')
250250
})
251251

252+
test('Resolving ## prefixed pattern with imports field', async () => {
253+
// subpath imports keys may contain more than one leading `#` (e.g. `##/*`)
254+
expect(await page.textContent('.imports-double-hash')).toMatch('[success]')
255+
})
256+
257+
test('Resolving key containing # with imports field', async () => {
258+
// subpath imports keys may contain `#` outside the leading position
259+
expect(await page.textContent('.imports-mid-hash')).toMatch('[success]')
260+
})
261+
262+
test('Resolving key containing ? with imports field', async () => {
263+
// subpath imports keys may contain `?` and are matched literally,
264+
// taking precedence over stripping it as a query postfix
265+
expect(await page.textContent('.imports-question-mark')).toMatch('[success]')
266+
})
267+
268+
test('Resolving with hash postfix with imports field', async () => {
269+
expect(await page.textContent('.imports-hash-hash')).toBe(
270+
'[success] subpath imports #hash',
271+
)
272+
})
273+
274+
test('Resolving #hash?query with imports field', async () => {
275+
expect(await page.textContent('.imports-hash-query')).toBe(
276+
'[success] subpath imports #hash',
277+
)
278+
})
279+
280+
test('Resolving #mid#hash#fragment?query with imports field', async () => {
281+
expect(await page.textContent('.imports-mid-hash-postfix')).toBe(
282+
'[success] subpath imports with # inside key',
283+
)
284+
})
285+
286+
test('Resolving #question?mark?query#fragment with imports field', async () => {
287+
expect(await page.textContent('.imports-question-mark-postfix')).toBe(
288+
'[success] subpath imports with ? inside key',
289+
)
290+
})
291+
252292
test("Resolve doesn't interrupt page request with trailing query and .css", async () => {
253293
await page.goto(viteTestUrl + '/?test.css')
254294
expect(await page.locator('vite-error-overlay').count()).toBe(0)
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
export const msg = '[success] subpath imports with ## prefixed pattern'
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
export const msg = '[success] subpath imports #hash'
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
import { msg } from '#hash#hash'
2+
3+
export { msg }
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
export const msg = '[success] subpath imports with # inside key'
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
export const msg = '[success] subpath imports with ? inside key'

‎playground/resolve/index.html‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,27 @@ <h2>Resolving dot-prefixed directory with imports field</h2>
7373
<h2>Resolving #/ root alias pattern with imports field</h2>
7474
<p class="imports-root-slash">fail</p>
7575

76+
<h2>Resolving ## prefixed pattern with imports field</h2>
77+
<p class="imports-double-hash">fail</p>
78+
79+
<h2>Resolving key containing # with imports field</h2>
80+
<p class="imports-mid-hash">fail</p>
81+
82+
<h2>Resolving key containing ? with imports field</h2>
83+
<p class="imports-question-mark">fail</p>
84+
85+
<h2>Resolving with hash postfix with imports field</h2>
86+
<p class="imports-hash-hash">fail</p>
87+
88+
<h2>Resolving #hash?query with imports field</h2>
89+
<p class="imports-hash-query">fail</p>
90+
91+
<h2>Resolving #mid#hash#fragment?query with imports field</h2>
92+
<p class="imports-mid-hash-postfix">fail</p>
93+
94+
<h2>Resolving #question?mark?query#fragment with imports field</h2>
95+
<p class="imports-question-mark-postfix">fail</p>
96+
7697
<h2>Resolve /index.*</h2>
7798
<p class="index">fail</p>
7899

@@ -285,6 +306,27 @@ <h2>utf8-bom-package</h2>
285306
import { msg as importsRootSlash } from '#/index.js'
286307
text('.imports-root-slash', importsRootSlash)
287308

309+
import { msg as importsDoubleHash } from '##double/index.js'
310+
text('.imports-double-hash', importsDoubleHash)
311+
312+
import { msg as importsMidHash } from '#mid#hash'
313+
text('.imports-mid-hash', importsMidHash)
314+
315+
import { msg as importsQuestionMark } from '#question?mark'
316+
text('.imports-question-mark', importsQuestionMark)
317+
318+
import { msg as importsHashHash } from './imports-path/importer-hash-hash.js'
319+
text('.imports-hash-hash', importsHashHash)
320+
321+
import { msg as importsHashQuery } from '#hash?query'
322+
text('.imports-hash-query', importsHashQuery)
323+
324+
import { msg as importsMidHashPostfix } from '#mid#hash#fragment?query'
325+
text('.imports-mid-hash-postfix', importsMidHashPostfix)
326+
327+
import { msg as importsQuestionMarkPostfix } from '#question?mark?query#fragment'
328+
text('.imports-question-mark-postfix', importsQuestionMarkPostfix)
329+
288330
// implicit index resolving
289331
import { foo } from './util'
290332
text('.index', foo())

0 commit comments

Comments
 (0)