Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(analysis): warnings for dynamic imports that use static template literals #14458

Merged
merged 6 commits into from Sep 28, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
17 changes: 14 additions & 3 deletions packages/vite/src/node/plugins/importAnalysis.ts
Expand Up @@ -79,6 +79,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 @@ -423,12 +425,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 @@ -466,6 +469,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
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
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
@@ -0,0 +1 @@
export const self = 'dynamic-import-static'