Skip to content

Commit 0c6d289

Browse files
Dunqingsapphi-red
authored andcommitted
fix(analysis): warnings for dynamic imports that use static template literals (#14458)
Co-authored-by: 翠 / green <green@sapphi.red>
1 parent 269aa43 commit 0c6d289

File tree

4 files changed

+21
-3
lines changed

4 files changed

+21
-3
lines changed

packages/vite/src/node/plugins/importAnalysis.ts

+14-3
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,8 @@ export const hasViteIgnoreRE = /\/\*\s*@vite-ignore\s*\*\//
8282
const cleanUpRawUrlRE = /\/\*[\s\S]*?\*\/|([^\\:]|^)\/\/.*$/gm
8383
const urlIsStringRE = /^(?:'.*'|".*"|`.*`)$/
8484

85+
const templateLiteralRE = /^\s*`(.*)`\s*$/
86+
8587
interface UrlPosition {
8688
url: string
8789
start: number
@@ -426,12 +428,13 @@ export function importAnalysisPlugin(config: ResolvedConfig): Plugin {
426428
ss: expStart,
427429
se: expEnd,
428430
d: dynamicIndex,
429-
// #2083 User may use escape path,
430-
// so use imports[index].n to get the unescaped string
431-
n: specifier,
432431
a: assertIndex,
433432
} = importSpecifier
434433

434+
// #2083 User may use escape path,
435+
// so use imports[index].n to get the unescaped string
436+
let specifier = importSpecifier.n
437+
435438
const rawUrl = source.slice(start, end)
436439

437440
// check import.meta usage
@@ -469,6 +472,14 @@ export function importAnalysisPlugin(config: ResolvedConfig): Plugin {
469472
hasEnv = true
470473
}
471474
return
475+
} else if (templateLiteralRE.test(rawUrl)) {
476+
// If the import has backticks but isn't transformed as a glob import
477+
// (as there's nothing to glob), check if it's simply a plain string.
478+
// If so, we can replace the specifier as a plain string to prevent
479+
// an incorrect "cannot be analyzed" warning.
480+
if (!(rawUrl.includes('${') && rawUrl.includes('}'))) {
481+
specifier = rawUrl.replace(templateLiteralRE, '$1')
482+
}
472483
}
473484

474485
const isDynamicImport = dynamicIndex > -1

playground/dynamic-import/index.html

+2
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,8 @@
3535

3636
<div class="dynamic-import-self"></div>
3737

38+
<div class="dynamic-import-static"></div>
39+
3840
<div class="dynamic-import-nested-self"></div>
3941

4042
<script type="module" src="./nested/index.js"></script>

playground/dynamic-import/nested/index.js

+4
Original file line numberDiff line numberDiff line change
@@ -131,4 +131,8 @@ import(`../nested/nested/${base}.js`).then((mod) => {
131131
text('.dynamic-import-nested-self', mod.self)
132132
})
133133

134+
import(`../nested/static.js`).then((mod) => {
135+
text('.dynamic-import-static', mod.self)
136+
})
137+
134138
console.log('index.js')
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
export const self = 'dynamic-import-static'

0 commit comments

Comments
 (0)