diff --git a/packages/vite/src/node/plugins/importAnalysis.ts b/packages/vite/src/node/plugins/importAnalysis.ts index ced27abf1529a1..45e8a38788353c 100644 --- a/packages/vite/src/node/plugins/importAnalysis.ts +++ b/packages/vite/src/node/plugins/importAnalysis.ts @@ -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 @@ -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 @@ -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 diff --git a/playground/dynamic-import/index.html b/playground/dynamic-import/index.html index 31cf128ddd12d1..afc5c03f8b862a 100644 --- a/playground/dynamic-import/index.html +++ b/playground/dynamic-import/index.html @@ -35,6 +35,8 @@
+ + diff --git a/playground/dynamic-import/nested/index.js b/playground/dynamic-import/nested/index.js index 180dd6b5ad3b6b..25a6426e3f7ee1 100644 --- a/playground/dynamic-import/nested/index.js +++ b/playground/dynamic-import/nested/index.js @@ -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') diff --git a/playground/dynamic-import/nested/static.js b/playground/dynamic-import/nested/static.js new file mode 100644 index 00000000000000..02dd476388a6e4 --- /dev/null +++ b/playground/dynamic-import/nested/static.js @@ -0,0 +1 @@ +export const self = 'dynamic-import-static'