diff --git a/packages/compiler-sfc/__tests__/__snapshots__/compileScript.spec.ts.snap b/packages/compiler-sfc/__tests__/__snapshots__/compileScript.spec.ts.snap
index 5e30973ac..85aa31337 100644
--- a/packages/compiler-sfc/__tests__/__snapshots__/compileScript.spec.ts.snap
+++ b/packages/compiler-sfc/__tests__/__snapshots__/compileScript.spec.ts.snap
@@ -206,7 +206,7 @@ return { x }
exports[`SFC compile
- {{ x }} {{ yy }}
+ {{ x }} {{ yy }} {{ x$y }}
FooBar
@@ -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 }`
+ )
})
})
diff --git a/packages/compiler-sfc/src/compileScript.ts b/packages/compiler-sfc/src/compileScript.ts
index 320c00b52..89a33f2ec 100644
--- a/packages/compiler-sfc/src/compileScript.ts
+++ b/packages/compiler-sfc/src/compileScript.ts
@@ -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] = {