]> git.ipfire.org Git - thirdparty/vuejs/core.git/commitdiff
chore(compiler-sfc): emit compiler error against incorrect ref sugar usage
authorEvan You <yyx990803@gmail.com>
Tue, 10 Aug 2021 18:57:47 +0000 (14:57 -0400)
committerEvan You <yyx990803@gmail.com>
Tue, 10 Aug 2021 18:57:47 +0000 (14:57 -0400)
packages/compiler-sfc/__tests__/compileScriptRefSugar.spec.ts
packages/compiler-sfc/src/compileScript.ts

index 59964d8510245234a2a65df286c37e8e02102a77..53172fa755a50faa0f70fc1a906e4913920be639 100644 (file)
@@ -366,5 +366,26 @@ describe('<script setup> ref sugar', () => {
         )
       ).toThrow(`cannot reference locally declared variables`)
     })
+
+    test('warn usage in non-init positions', () => {
+      expect(() =>
+        compile(
+          `<script setup>
+      let bar = $ref(1)
+      bar = $ref(2)
+    </script>`,
+          { refSugar: true }
+        )
+      ).toThrow(`$ref can only be used directly as a variable initializer`)
+
+      expect(() =>
+        compile(
+          `<script setup>
+      let bar = { foo: $computed(1) }
+    </script>`,
+          { refSugar: true }
+        )
+      ).toThrow(`$computed can only be used directly as a variable initializer`)
+    })
   })
 })
index 9a558f25f869d2ddf766068d4911f45f8e168fa6..000dff41230b0b827a03dc979ddbfec5260b31bb 100644 (file)
@@ -1096,7 +1096,7 @@ export function compileScript(
 
   // 3. Do a full walk to rewrite identifiers referencing let exports with ref
   // value access
-  if (enableRefSugar && Object.keys(refBindings).length) {
+  if (enableRefSugar) {
     const onIdent = (id: Identifier, parent: Node, parentStack: Node[]) => {
       if (refBindings[id.name] && !refIdentifiers.has(id)) {
         if (isStaticProperty(parent) && parent.shorthand) {
@@ -1115,13 +1115,26 @@ export function compileScript(
       }
     }
 
-    const onNode = (node: Node) => {
+    const onNode = (node: Node, parent: Node) => {
       if (isCallOf(node, $RAW)) {
         s.remove(
           node.callee.start! + startOffset,
           node.callee.end! + startOffset
         )
         return false // skip walk
+      } else if (
+        parent &&
+        isCallOf(
+          node,
+          id => id === $REF || id === $FROM_REFS || id === $COMPUTED
+        ) &&
+        (parent.type !== 'VariableDeclarator' || node !== parent.init)
+      ) {
+        error(
+          // @ts-ignore
+          `${node.callee.name} can only be used directly as a variable initializer.`,
+          node
+        )
       }
     }