Skip to content

Commit e42d779

Browse files
committed
chore(compiler-sfc): emit compiler error against incorrect ref sugar usage
1 parent 2224610 commit e42d779

File tree

2 files changed

+36
-2
lines changed

2 files changed

+36
-2
lines changed

packages/compiler-sfc/__tests__/compileScriptRefSugar.spec.ts

+21
Original file line numberDiff line numberDiff line change
@@ -366,5 +366,26 @@ describe('<script setup> ref sugar', () => {
366366
)
367367
).toThrow(`cannot reference locally declared variables`)
368368
})
369+
370+
test('warn usage in non-init positions', () => {
371+
expect(() =>
372+
compile(
373+
`<script setup>
374+
let bar = $ref(1)
375+
bar = $ref(2)
376+
</script>`,
377+
{ refSugar: true }
378+
)
379+
).toThrow(`$ref can only be used directly as a variable initializer`)
380+
381+
expect(() =>
382+
compile(
383+
`<script setup>
384+
let bar = { foo: $computed(1) }
385+
</script>`,
386+
{ refSugar: true }
387+
)
388+
).toThrow(`$computed can only be used directly as a variable initializer`)
389+
})
369390
})
370391
})

packages/compiler-sfc/src/compileScript.ts

+15-2
Original file line numberDiff line numberDiff line change
@@ -1096,7 +1096,7 @@ export function compileScript(
10961096

10971097
// 3. Do a full walk to rewrite identifiers referencing let exports with ref
10981098
// value access
1099-
if (enableRefSugar && Object.keys(refBindings).length) {
1099+
if (enableRefSugar) {
11001100
const onIdent = (id: Identifier, parent: Node, parentStack: Node[]) => {
11011101
if (refBindings[id.name] && !refIdentifiers.has(id)) {
11021102
if (isStaticProperty(parent) && parent.shorthand) {
@@ -1115,13 +1115,26 @@ export function compileScript(
11151115
}
11161116
}
11171117

1118-
const onNode = (node: Node) => {
1118+
const onNode = (node: Node, parent: Node) => {
11191119
if (isCallOf(node, $RAW)) {
11201120
s.remove(
11211121
node.callee.start! + startOffset,
11221122
node.callee.end! + startOffset
11231123
)
11241124
return false // skip walk
1125+
} else if (
1126+
parent &&
1127+
isCallOf(
1128+
node,
1129+
id => id === $REF || id === $FROM_REFS || id === $COMPUTED
1130+
) &&
1131+
(parent.type !== 'VariableDeclarator' || node !== parent.init)
1132+
) {
1133+
error(
1134+
// @ts-ignore
1135+
`${node.callee.name} can only be used directly as a variable initializer.`,
1136+
node
1137+
)
11251138
}
11261139
}
11271140

0 commit comments

Comments
 (0)