Skip to content

Commit

Permalink
fix(analysis): warnings for dynamic imports that use static template …
Browse files Browse the repository at this point in the history
…literals (#14458)

Co-authored-by: 翠 / green <green@sapphi.red>
  • Loading branch information
2 people authored and bluwy committed Oct 3, 2023
1 parent 269aa43 commit 0c6d289
Show file tree
Hide file tree
Showing 4 changed files with 21 additions and 3 deletions.
17 changes: 14 additions & 3 deletions packages/vite/src/node/plugins/importAnalysis.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,8 @@ export const hasViteIgnoreRE = /\/\*\s*@vite-ignore\s*\*\//
const cleanUpRawUrlRE = /\/\*[\s\S]*?\*\/|([^\\:]|^)\/\/.*$/gm
const urlIsStringRE = /^(?:'.*'|".*"|`.*`)$/

const templateLiteralRE = /^\s*`(.*)`\s*$/

interface UrlPosition {
url: string
start: number
Expand Down Expand Up @@ -426,12 +428,13 @@ export function importAnalysisPlugin(config: ResolvedConfig): Plugin {
ss: expStart,
se: expEnd,
d: dynamicIndex,
// #2083 User may use escape path,
// so use imports[index].n to get the unescaped string
n: specifier,
a: assertIndex,
} = importSpecifier

// #2083 User may use escape path,
// so use imports[index].n to get the unescaped string
let specifier = importSpecifier.n

const rawUrl = source.slice(start, end)

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

const isDynamicImport = dynamicIndex > -1
Expand Down
2 changes: 2 additions & 0 deletions playground/dynamic-import/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,8 @@

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

<div class="dynamic-import-static"></div>

<div class="dynamic-import-nested-self"></div>

<script type="module" src="./nested/index.js"></script>
Expand Down
4 changes: 4 additions & 0 deletions playground/dynamic-import/nested/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -131,4 +131,8 @@ import(`../nested/nested/${base}.js`).then((mod) => {
text('.dynamic-import-nested-self', mod.self)
})

import(`../nested/static.js`).then((mod) => {
text('.dynamic-import-static', mod.self)
})

console.log('index.js')
1 change: 1 addition & 0 deletions playground/dynamic-import/nested/static.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export const self = 'dynamic-import-static'

0 comments on commit 0c6d289

Please sign in to comment.