Skip to content

Commit a6e5f82

Browse files
committed
fix(compiler-sfc): properly analyze destructured bindings with dynamic keys
fix #4540
1 parent 781d2d4 commit a6e5f82

File tree

3 files changed

+40
-13
lines changed

3 files changed

+40
-13
lines changed

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

+13
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,19 @@ export default /*#__PURE__*/ Object.assign(__default__, {
9696
})"
9797
`;
9898
99+
exports[`SFC compile <script setup> binding analysis for destructur 1`] = `
100+
"export default {
101+
setup(__props, { expose }) {
102+
expose()
103+
104+
const { foo, b: bar, ['x' + 'y']: baz, x: { y, zz: { z }}} = {}
105+
106+
return { foo, bar, baz, y, z }
107+
}
108+
109+
}"
110+
`;
111+
99112
exports[`SFC compile <script setup> defineEmits() 1`] = `
100113
"export default {
101114
emits: ['foo', 'bar'],

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

+17
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,23 @@ describe('SFC compile <script setup>', () => {
3636
assertCode(content)
3737
})
3838

39+
test('binding analysis for destructur', () => {
40+
const { content, bindings } = compile(`
41+
<script setup>
42+
const { foo, b: bar, ['x' + 'y']: baz, x: { y, zz: { z }}} = {}
43+
</script>
44+
`)
45+
expect(content).toMatch('return { foo, bar, baz, y, z }')
46+
expect(bindings).toStrictEqual({
47+
foo: BindingTypes.SETUP_MAYBE_REF,
48+
bar: BindingTypes.SETUP_MAYBE_REF,
49+
baz: BindingTypes.SETUP_MAYBE_REF,
50+
y: BindingTypes.SETUP_MAYBE_REF,
51+
z: BindingTypes.SETUP_MAYBE_REF
52+
})
53+
assertCode(content)
54+
})
55+
3956
test('defineProps()', () => {
4057
const { content, bindings } = compile(`
4158
<script setup>

packages/compiler-sfc/src/compileScript.ts

+10-13
Original file line numberDiff line numberDiff line change
@@ -1347,19 +1347,16 @@ function walkObjectPattern(
13471347
) {
13481348
for (const p of node.properties) {
13491349
if (p.type === 'ObjectProperty') {
1350-
// key can only be Identifier in ObjectPattern
1351-
if (p.key.type === 'Identifier') {
1352-
if (p.key === p.value) {
1353-
// const { x } = ...
1354-
const type = isDefineCall
1355-
? BindingTypes.SETUP_CONST
1356-
: isConst
1357-
? BindingTypes.SETUP_MAYBE_REF
1358-
: BindingTypes.SETUP_LET
1359-
registerBinding(bindings, p.key, type)
1360-
} else {
1361-
walkPattern(p.value, bindings, isConst, isDefineCall)
1362-
}
1350+
if (p.key.type === 'Identifier' && p.key === p.value) {
1351+
// shorthand: const { x } = ...
1352+
const type = isDefineCall
1353+
? BindingTypes.SETUP_CONST
1354+
: isConst
1355+
? BindingTypes.SETUP_MAYBE_REF
1356+
: BindingTypes.SETUP_LET
1357+
registerBinding(bindings, p.key, type)
1358+
} else {
1359+
walkPattern(p.value, bindings, isConst, isDefineCall)
13631360
}
13641361
} else {
13651362
// ...rest

0 commit comments

Comments
 (0)