fix(compiler-sfc): fix import usage detection for names containing $

fix #4274
This commit is contained in:
Evan You 2021-08-09 12:17:22 -04:00
parent 4781965cc2
commit 88a4504e82
3 changed files with 13 additions and 8 deletions

View File

@ -206,7 +206,7 @@ return { x }
exports[`SFC compile <script setup> imports imports not used in <template> should not be exposed 1`] = ` exports[`SFC compile <script setup> imports imports not used in <template> should not be exposed 1`] = `
"import { defineComponent as _defineComponent } from 'vue' "import { defineComponent as _defineComponent } from 'vue'
import { FooBar, FooBaz, FooQux, vMyDir, x, y, z } from './x' import { FooBar, FooBaz, FooQux, vMyDir, x, y, z, x$y } from './x'
export default _defineComponent({ export default _defineComponent({
setup(__props, { expose }) { setup(__props, { expose }) {
@ -214,7 +214,7 @@ export default _defineComponent({
const fooBar: FooBar = 1 const fooBar: FooBar = 1
return { fooBar, FooBaz, FooQux, vMyDir, x, z } return { fooBar, FooBaz, FooQux, vMyDir, x, z, x$y }
} }
})" })"

View File

@ -213,11 +213,11 @@ defineExpose({ foo: 123 })
test('imports not used in <template> should not be exposed', () => { test('imports not used in <template> should not be exposed', () => {
const { content } = compile(` const { content } = compile(`
<script setup lang="ts"> <script setup lang="ts">
import { FooBar, FooBaz, FooQux, vMyDir, x, y, z } from './x' import { FooBar, FooBaz, FooQux, vMyDir, x, y, z, x$y } from './x'
const fooBar: FooBar = 1 const fooBar: FooBar = 1
</script> </script>
<template> <template>
<FooBaz v-my-dir>{{ x }} {{ yy }}</FooBaz> <FooBaz v-my-dir>{{ x }} {{ yy }} {{ x$y }}</FooBaz>
<foo-qux/> <foo-qux/>
<div :id="z + 'y'">FooBar</div> <div :id="z + 'y'">FooBar</div>
</template> </template>
@ -229,7 +229,10 @@ defineExpose({ foo: 123 })
// vMyDir: used as directive v-my-dir // vMyDir: used as directive v-my-dir
// x: used in interpolation // x: used in interpolation
// y: should not be matched by {{ yy }} or 'y' in binding exps // y: should not be matched by {{ yy }} or 'y' in binding exps
expect(content).toMatch(`return { fooBar, FooBaz, FooQux, vMyDir, x, z }`) // x$y: #4274 should escape special chars when creating Regex
expect(content).toMatch(
`return { fooBar, FooBaz, FooQux, vMyDir, x, z, x$y }`
)
}) })
}) })

View File

@ -332,9 +332,11 @@ export function compileScript(
let isUsedInTemplate = true let isUsedInTemplate = true
if (isTS && sfc.template && !sfc.template.src) { if (isTS && sfc.template && !sfc.template.src) {
isUsedInTemplate = new RegExp(`\\b${local}\\b`).test( isUsedInTemplate = new RegExp(
resolveTemplateUsageCheckString(sfc) // #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))
} }
userImports[local] = { userImports[local] = {