Skip to content

Commit b78e2f1

Browse files
authored
feat: support subpath imports in dynamic import statements (#23185)
1 parent a500dee commit b78e2f1

7 files changed

Lines changed: 53 additions & 10 deletions

File tree

‎docs/guide/features.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -655,7 +655,7 @@ Note that variables only represent file names one level deep. If `file` is `'foo
655655

656656
Also note that the dynamic import must match the following rules to be bundled:
657657

658-
- Imports must start with `./` or `../`: ``import(`./dir/${foo}.js`)`` is valid, but ``import(`${foo}.js`)`` is not.
658+
- Imports must start with `./` or `../` or `#`: ``import(`./dir/${foo}.js`)`` is valid, but ``import(`${foo}.js`)`` is not.
659659
- Imports must end with a file extension: ``import(`./dir/${foo}.js`)`` is valid, but ``import(`./dir/${foo}`)`` is not.
660660
- Imports to the own directory must specify a file name pattern: ``import(`./prefix-${foo}.js`)`` is valid, but ``import(`./${foo}.js`)`` is not.
661661

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

Lines changed: 21 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { posix } from 'node:path'
1+
import path, { posix } from 'node:path'
22
import MagicString from 'magic-string'
33
import { init, parse as parseImports } from 'es-module-lexer'
44
import type { ImportSpecifier } from 'es-module-lexer'
@@ -21,7 +21,9 @@ import {
2121
} from '../utils'
2222
import type { Environment } from '../environment'
2323
import { perEnvironmentState } from '../environment'
24+
import type { PartialEnvironment } from '../baseEnvironment'
2425
import { hasViteIgnoreRE } from './importAnalysis'
26+
import { resolveSubpathImports } from './resolve'
2527
import { workerOrSharedWorkerRE } from './worker'
2628

2729
export const dynamicImportHelperId = '\0vite/dynamic-import-helper.js'
@@ -172,6 +174,22 @@ export function dynamicImportVarsPlugin(config: ResolvedConfig): Plugin {
172174
tryIndex: false,
173175
extensions: [],
174176
})
177+
const resolveDynamicImport = (
178+
environment: PartialEnvironment,
179+
id: string,
180+
importer?: string,
181+
) => {
182+
const subpathImports = resolveSubpathImports(id, importer, {
183+
...environment.config.resolve,
184+
packageCache: config.packageCache,
185+
isProduction: config.isProduction,
186+
isRequire: false,
187+
})
188+
if (subpathImports && importer) {
189+
return normalizePath(path.resolve(path.dirname(importer), subpathImports))
190+
}
191+
return resolve(environment, id, importer)
192+
}
175193

176194
const getFilter = perEnvironmentState((environment: Environment) => {
177195
const { include, exclude } =
@@ -191,7 +209,7 @@ export function dynamicImportVarsPlugin(config: ResolvedConfig): Plugin {
191209
include,
192210
exclude,
193211
resolver(id, importer) {
194-
return resolve(environment, id, importer)
212+
return resolveDynamicImport(environment, id, importer)
195213
},
196214
sourcemap: !!environment.config.build.sourcemap,
197215
})
@@ -264,7 +282,7 @@ export function dynamicImportVarsPlugin(config: ResolvedConfig): Plugin {
264282
result = await transformDynamicImport(
265283
source.slice(start, end),
266284
importer,
267-
(id, importer) => resolve(environment, id, importer),
285+
(id, importer) => resolveDynamicImport(environment, id, importer),
268286
config.root,
269287
)
270288
} catch (error) {

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

Lines changed: 15 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -350,11 +350,10 @@ export function oxcResolvePlugin(
350350
)
351351
return newResolvedId === resolvedId ? undefined : newResolvedId
352352
},
353-
resolveSubpathImports(id, importer, isRequire, scan) {
353+
resolveSubpathImports(id, importer, isRequire) {
354354
return resolveSubpathImports(id, importer, {
355355
...options,
356356
isRequire: resolveOptions.isRequire ?? isRequire,
357-
scan,
358357
})
359358
},
360359

@@ -489,11 +488,18 @@ function optimizerResolvePlugin(
489488
}
490489
}
491490

492-
function resolveSubpathImports(
491+
export function resolveSubpathImports(
493492
id: string,
494493
importer: string | undefined,
495-
options: InternalResolveOptions,
496-
) {
494+
options: Pick<
495+
InternalResolveOptions,
496+
| 'packageCache'
497+
| 'conditions'
498+
| 'externalConditions'
499+
| 'isProduction'
500+
| 'isRequire'
501+
>,
502+
): string | undefined {
497503
if (!importer || !id.startsWith(subpathImportsPrefix)) return
498504
const basedir = path.dirname(importer)
499505
const pkgData = findNearestPackageData(basedir, options.packageCache)
@@ -1027,7 +1033,10 @@ function getConditions(
10271033
function resolveExportsOrImports(
10281034
pkg: PackageData['data'],
10291035
key: string,
1030-
options: InternalResolveOptions,
1036+
options: Pick<
1037+
InternalResolveOptions,
1038+
'conditions' | 'externalConditions' | 'isProduction' | 'isRequire'
1039+
>,
10311040
type: 'imports' | 'exports',
10321041
externalize?: boolean,
10331042
) {

‎playground/dynamic-import/__tests__/dynamic-import.spec.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -115,6 +115,12 @@ test('should load dynamic import with vars alias', async () => {
115115
.toMatch('hi')
116116
})
117117

118+
test('should load dynamic import with vars subpath imports', async () => {
119+
await expect
120+
.poll(() => page.textContent('.dynamic-import-with-vars-subpath-imports'))
121+
.toMatch('hi')
122+
})
123+
118124
test('should load dynamic import with vars raw', async () => {
119125
await expect
120126
.poll(() => page.textContent('.dynamic-import-with-vars-raw'))

‎playground/dynamic-import/index.html‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,9 @@
2525
<p>dynamic-import-with-vars-alias</p>
2626
<div class="dynamic-import-with-vars-alias">todo</div>
2727

28+
<p>dynamic-import-with-vars-subpath-imports</p>
29+
<div class="dynamic-import-with-vars-subpath-imports">todo</div>
30+
2831
<p>dynamic-import-with-vars-raw</p>
2932
<div class="dynamic-import-with-vars-raw">todo</div>
3033

‎playground/dynamic-import/nested/index.js‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -127,6 +127,10 @@ import(`@/${base}.js`).then((mod) => {
127127
text('.dynamic-import-with-vars-alias', mod.hi())
128128
})
129129

130+
import(`#alias/${base}.js`).then((mod) => {
131+
text('.dynamic-import-with-vars-subpath-imports', mod.hi())
132+
})
133+
130134
base = 'self'
131135
import(`../nested/${base}.js`).then((mod) => {
132136
text('.dynamic-import-self', mod.self)

‎playground/dynamic-import/package.json‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,9 @@
33
"private": true,
44
"version": "0.0.0",
55
"type": "module",
6+
"imports": {
7+
"#alias/*": "./alias/*"
8+
},
69
"scripts": {
710
"dev": "vite",
811
"build": "vite build",

0 commit comments

Comments
 (0)