Parcourir la source

fix(sfc): ensure consistent dev/prod behavior for non-reactive variables declared in `<script setup>`

fix #5655
Evan You il y a 3 ans
Parent
commit
5a3d45ae29

+ 1 - 1
packages/compiler-sfc/__tests__/__snapshots__/compileScript.spec.ts.snap

@@ -1280,7 +1280,7 @@ export default {
       function c() {}
       class d {}
       
-return { aa, bb, cc, dd, a, b, c, d, xx, x }
+return { get aa() { return aa }, bb, cc, dd, get a() { return a }, b, c, d, xx, x }
 }
 
 }"

+ 2 - 2
packages/compiler-sfc/__tests__/__snapshots__/compileScriptRefTransform.spec.ts.snap

@@ -15,7 +15,7 @@ export default {
     let c = () => {}
     let d
     
-return { foo, a, b, c, d, ref, shallowRef }
+return { foo, a, b, get c() { return c }, get d() { return d }, ref, shallowRef }
 }
 
 }"
@@ -36,7 +36,7 @@ export default {
     let c = () => {}
     let d
     
-return { foo, a, b, c, d }
+return { foo, a, b, get c() { return c }, get d() { return d } }
 }
 
 }"

+ 1 - 1
packages/compiler-sfc/__tests__/__snapshots__/cssVars.spec.ts.snap

@@ -84,7 +84,7 @@ _useCssVars(_ctx => ({
         let b = 200
         let foo = 300
         
-return { a, b, foo }
+return { get a() { return a }, get b() { return b }, get foo() { return foo } }
 }
 
 }"

+ 3 - 1
packages/compiler-sfc/__tests__/compileScript.spec.ts

@@ -20,7 +20,9 @@ describe('SFC compile <script setup>', () => {
       class dd {}
       </script>
       `)
-    expect(content).toMatch('return { aa, bb, cc, dd, a, b, c, d, xx, x }')
+    expect(content).toMatch(
+      'return { get aa() { return aa }, bb, cc, dd, get a() { return a }, b, c, d, xx, x }'
+    )
     expect(bindings).toStrictEqual({
       x: BindingTypes.SETUP_MAYBE_REF,
       a: BindingTypes.SETUP_LET,

+ 3 - 1
packages/compiler-sfc/__tests__/compileScriptRefTransform.spec.ts

@@ -32,7 +32,9 @@ describe('sfc ref transform', () => {
     // normal declarations left untouched
     expect(content).toMatch(`let c = () => {}`)
     expect(content).toMatch(`let d`)
-    expect(content).toMatch(`return { foo, a, b, c, d, ref, shallowRef }`)
+    expect(content).toMatch(
+      `return { foo, a, b, get c() { return c }, get d() { return d }, ref, shallowRef }`
+    )
     assertCode(content)
     expect(bindings).toStrictEqual({
       foo: BindingTypes.SETUP_REF,

+ 9 - 1
packages/compiler-sfc/src/compileScript.ts

@@ -1484,7 +1484,15 @@ export function compileScript(
         allBindings[key] = true
       }
     }
-    returned = `{ ${Object.keys(allBindings).join(', ')} }`
+    returned = `{ `
+    for (const key in allBindings) {
+      if (bindingMetadata[key] === BindingTypes.SETUP_LET) {
+        returned += `get ${key}() { return ${key} }, `
+      } else {
+        returned += `${key}, `
+      }
+    }
+    returned = returned.replace(/, $/, '') + ` }`
   } else {
     // inline mode
     if (sfc.template && !sfc.template.src) {