Skip to content

Commit

Permalink
fix(compiler-sfc): fix import usage detection for names containing $
Browse files Browse the repository at this point in the history
fix #4274
  • Loading branch information
yyx990803 committed Aug 9, 2021
1 parent 4781965 commit 88a4504
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 8 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 } from './x'
import { FooBar, FooBaz, FooQux, vMyDir, x, y, z, x$y } from './x'
export default _defineComponent({
setup(__props, { expose }) {
expose()
const fooBar: FooBar = 1
return { fooBar, FooBaz, FooQux, vMyDir, x, z }
return { fooBar, FooBaz, FooQux, vMyDir, x, z, x$y }
}
})"
Expand Down
9 changes: 6 additions & 3 deletions packages/compiler-sfc/__tests__/compileScript.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -213,11 +213,11 @@ 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 } from './x'
import { FooBar, FooBaz, FooQux, vMyDir, x, y, z, x$y } from './x'
const fooBar: FooBar = 1
</script>
<template>
<FooBaz v-my-dir>{{ x }} {{ yy }}</FooBaz>
<FooBaz v-my-dir>{{ x }} {{ yy }} {{ x$y }}</FooBaz>
<foo-qux/>
<div :id="z + 'y'">FooBar</div>
</template>
Expand All @@ -229,7 +229,10 @@ defineExpose({ foo: 123 })
// vMyDir: used as directive v-my-dir
// x: used in interpolation
// 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 }`
)
})
})

Expand Down
8 changes: 5 additions & 3 deletions packages/compiler-sfc/src/compileScript.ts
Original file line number Diff line number Diff line change
Expand Up @@ -332,9 +332,11 @@ export function compileScript(

let isUsedInTemplate = true
if (isTS && sfc.template && !sfc.template.src) {
isUsedInTemplate = new RegExp(`\\b${local}\\b`).test(
resolveTemplateUsageCheckString(sfc)
)
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))
}

userImports[local] = {
Expand Down

0 comments on commit 88a4504

Please sign in to comment.