Skip to content

Commit 568bdab

Browse files
authoredJan 25, 2023
fix: scope tracking for shadowing variables in blocks (#11806) (#11811)
1 parent 4bbebf3 commit 568bdab

File tree

2 files changed

+36
-4
lines changed

2 files changed

+36
-4
lines changed
 

‎packages/vite/src/node/ssr/__tests__/ssrTransform.spec.ts

+30
Original file line numberDiff line numberDiff line change
@@ -812,3 +812,33 @@ function test() {
812812
}"
813813
`)
814814
})
815+
816+
// #11806
817+
test('track scope by blocks', async () => {
818+
expect(
819+
await ssrTransformSimpleCode(`
820+
import { foo, bar, baz } from 'foobar'
821+
function test() {
822+
[foo];
823+
{
824+
let foo = 10;
825+
let bar = 10;
826+
}
827+
try {} catch (baz){ baz };
828+
return bar;
829+
}`),
830+
).toMatchInlineSnapshot(`
831+
"
832+
const __vite_ssr_import_0__ = await __vite_ssr_import__(\\"foobar\\");
833+
834+
function test() {
835+
[__vite_ssr_import_0__.foo];
836+
{
837+
let foo = 10;
838+
let bar = 10;
839+
}
840+
try {} catch (baz){ baz };
841+
return __vite_ssr_import_0__.bar;
842+
}"
843+
`)
844+
})

‎packages/vite/src/node/ssr/ssrTransform.ts

+6-4
Original file line numberDiff line numberDiff line change
@@ -448,6 +448,8 @@ function walk(
448448
if (parentFunction) {
449449
handlePattern(node.id, parentFunction)
450450
}
451+
} else if (node.type === 'CatchClause' && node.param) {
452+
handlePattern(node.param, node)
451453
}
452454
},
453455

@@ -550,14 +552,14 @@ function isFunction(node: _Node): node is FunctionNode {
550552
return functionNodeTypeRE.test(node.type)
551553
}
552554

553-
const scopeNodeTypeRE =
554-
/(?:Function|Class)(?:Expression|Declaration)$|Method$|^IfStatement$/
555555
function findParentScope(
556556
parentStack: _Node[],
557557
isVar = false,
558558
): _Node | undefined {
559-
const regex = isVar ? functionNodeTypeRE : scopeNodeTypeRE
560-
return parentStack.find((i) => regex.test(i.type))
559+
const predicate = isVar
560+
? isFunction
561+
: (node: _Node) => node.type === 'BlockStatement'
562+
return parentStack.find(predicate)
561563
}
562564

563565
function isInDestructuringAssignment(

0 commit comments

Comments
 (0)