diff --git a/packages/compiler-sfc/src/compileScript.ts b/packages/compiler-sfc/src/compileScript.ts index 4a33f6e9..379ad6ab 100644 --- a/packages/compiler-sfc/src/compileScript.ts +++ b/packages/compiler-sfc/src/compileScript.ts @@ -113,7 +113,7 @@ export interface SFCScriptCompileOptions { templateOptions?: Partial } -interface ImportBinding { +export interface ImportBinding { isType: boolean imported: string source: string @@ -335,11 +335,7 @@ export function compileScript( let isUsedInTemplate = true if (isTS && sfc.template && !sfc.template.src && !sfc.template.lang) { - isUsedInTemplate = new RegExp( - // #4274 escape $ since it's a special char in regex - // (and is the only regex special char that is valid in identifiers) - `[^\\w$_]${local.replace(/\$/g, '\\$')}[^\\w$_]` - ).test(resolveTemplateUsageCheckString(sfc)) + isUsedInTemplate = isImportUsed(local, sfc) } userImports[local] = { @@ -1441,6 +1437,7 @@ export function compileScript( return { ...scriptSetup, bindings: bindingMetadata, + imports: userImports, content: s.toString(), map: genSourceMap ? (s.generateMap({ @@ -1960,7 +1957,7 @@ function getObjectOrArrayExpressionKeys(value: Node): string[] { const templateUsageCheckCache = createCache() -export function resolveTemplateUsageCheckString(sfc: SFCDescriptor) { +function resolveTemplateUsageCheckString(sfc: SFCDescriptor) { const { content, ast } = sfc.template! const cached = templateUsageCheckCache.get(content) if (cached) { @@ -2018,3 +2015,40 @@ function stripTemplateString(str: string): string { } return '' } + +function isImportUsed(local: string, sfc: SFCDescriptor): boolean { + return new RegExp( + // #4274 escape $ since it's a special char in regex + // (and is the only regex special char that is valid in identifiers) + `[^\\w$_]${local.replace(/\$/g, '\\$')}[^\\w$_]` + ).test(resolveTemplateUsageCheckString(sfc)) +} + +/** + * Note: this comparison assumes the prev/next script are already identical, + * and only checks the special case where