From: Evan You Date: Thu, 22 Jul 2021 16:04:46 +0000 (-0400) Subject: feat(compiler-sfc): avoid exposing imports not used in template X-Git-Tag: v3.2.0-beta.5~10 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=5a3ccfd9143700c7ca82d2911fe592d0658c5393;p=thirdparty%2Fvuejs%2Fcore.git feat(compiler-sfc): avoid exposing imports not used in template close #3183 --- diff --git a/packages/compiler-sfc/__tests__/__snapshots__/compileScript.spec.ts.snap b/packages/compiler-sfc/__tests__/__snapshots__/compileScript.spec.ts.snap index fde572c861..cc44a7ab10 100644 --- a/packages/compiler-sfc/__tests__/__snapshots__/compileScript.spec.ts.snap +++ b/packages/compiler-sfc/__tests__/__snapshots__/compileScript.spec.ts.snap @@ -204,6 +204,22 @@ return { x } }" `; +exports[`SFC compile + + `) + assertCode(content) + // FooBaz: used as PascalCase component + // FooQux: used as kebab-case component + // vMyDir: used as directive v-my-dir + // x: used in interpolation + expect(content).toMatch(`return { fooBar, FooBaz, FooQux, vMyDir, x }`) + }) }) describe('inlineTemplate mode', () => { diff --git a/packages/compiler-sfc/src/compileScript.ts b/packages/compiler-sfc/src/compileScript.ts index 432d977fa3..82b84528d0 100644 --- a/packages/compiler-sfc/src/compileScript.ts +++ b/packages/compiler-sfc/src/compileScript.ts @@ -12,7 +12,11 @@ import { TextRange } from './parse' import { parse as _parse, ParserOptions, ParserPlugin } from '@babel/parser' -import { babelParserDefaultPlugins, generateCodeFrame } from '@vue/shared' +import { + babelParserDefaultPlugins, + generateCodeFrame, + hyphenate +} from '@vue/shared' import { Node, Declaration, @@ -105,6 +109,7 @@ interface ImportBinding { source: string rangeNode: Node isFromSetup: boolean + isUsedInTemplate: boolean } interface VariableBinding { @@ -312,12 +317,21 @@ export function compileScript( if (source === 'vue' && imported) { userImportAlias[imported] = local } + + let isUsedInTemplate = true + if (sfc.template && !sfc.template.src) { + isUsedInTemplate = new RegExp( + `\\b(?:${local}|${hyphenate(local)})\\b` + ).test(sfc.template.content) + } + userImports[local] = { isType, imported: imported || 'default', source, rangeNode, - isFromSetup + isFromSetup, + isUsedInTemplate } } @@ -1279,7 +1293,7 @@ export function compileScript( // return bindings from setup const allBindings: Record = { ...setupBindings } for (const key in userImports) { - if (!userImports[key].isType) { + if (!userImports[key].isType && userImports[key].isUsedInTemplate) { allBindings[key] = true } }