Skip to content

Commit

Permalink
fix(compiler-sfc): fix import usage check in template strings in expr…
Browse files Browse the repository at this point in the history
…essions

fix #4340
  • Loading branch information
yyx990803 committed Aug 16, 2021
1 parent ad66295 commit f855ccb
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 6 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -206,15 +206,15 @@ return { x }
exports[`SFC compile <script setup> imports imports not used in <template> should not be exposed 1`] = `
"import { defineComponent as _defineComponent } from 'vue'
import { FooBar, FooBaz, FooQux, vMyDir, x, y, z, x$y, Last } from './x'
import { FooBar, FooBaz, FooQux, vMyDir, x, y, z, x$y, VAR, VAR2, VAR3, Last } from './x'
export default _defineComponent({
setup(__props, { expose }) {
expose()
const fooBar: FooBar = 1
return { fooBar, FooBaz, FooQux, vMyDir, x, z, x$y, Last }
return { fooBar, FooBaz, FooQux, vMyDir, x, z, x$y, VAR, VAR3, Last }
}
})"
Expand Down
8 changes: 5 additions & 3 deletions packages/compiler-sfc/__tests__/compileScript.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -213,27 +213,29 @@ defineExpose({ foo: 123 })
test('imports not used in <template> should not be exposed', () => {
const { content } = compile(`
<script setup lang="ts">
import { FooBar, FooBaz, FooQux, vMyDir, x, y, z, x$y, Last } from './x'
import { FooBar, FooBaz, FooQux, vMyDir, x, y, z, x$y, VAR, VAR2, VAR3, Last } from './x'
const fooBar: FooBar = 1
</script>
<template>
<FooBaz v-my-dir>{{ x }} {{ yy }} {{ x$y }}</FooBaz>
<foo-qux/>
<div :id="z + 'y'">FooBar</div>
{{ \`\${VAR}VAR2\${VAR3}\` }}
<Last/>
</template>
`)
assertCode(content)
// FooBar: should not be matched by plain text
// FooBaz: used as PascalCase component
// FooQux: used as kebab-case component
// vMyDir: used as directive v-my-dir
// x: used in interpolation
// y: should not be matched by {{ yy }} or 'y' in binding exps
// x$y: #4274 should escape special chars when creating Regex
// VAR & VAR3: #4340 interpolations in tempalte strings
expect(content).toMatch(
`return { fooBar, FooBaz, FooQux, vMyDir, x, z, x$y, Last }`
`return { fooBar, FooBaz, FooQux, vMyDir, x, z, x$y, VAR, VAR3, Last }`
)
assertCode(content)
})
})

Expand Down
12 changes: 11 additions & 1 deletion packages/compiler-sfc/src/compileScript.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2242,5 +2242,15 @@ function resolveTemplateUsageCheckString(sfc: SFCDescriptor) {
}

function stripStrings(exp: string) {
return exp.replace(/'[^']+'|"[^"]+"|`[^`]+`/g, '')
return exp
.replace(/'[^']+'|"[^"]+"/g, '')
.replace(/`[^`]+`/g, stripTemplateString)
}

function stripTemplateString(str: string): string {
const interpMatch = str.match(/\${[^}]+}/g)
if (interpMatch) {
return interpMatch.map(m => m.slice(2, -1)).join(',')
}
return ''
}

0 comments on commit f855ccb

Please sign in to comment.