From 568bdabffe793ea8db03b35667f117a1207f4fbe Mon Sep 17 00:00:00 2001 From: gtmnayan <50981692+gtm-nayan@users.noreply.github.com> Date: Wed, 25 Jan 2023 22:32:19 +0545 Subject: [PATCH] fix: scope tracking for shadowing variables in blocks (#11806) (#11811) --- .../node/ssr/__tests__/ssrTransform.spec.ts | 30 +++++++++++++++++++ packages/vite/src/node/ssr/ssrTransform.ts | 10 ++++--- 2 files changed, 36 insertions(+), 4 deletions(-) diff --git a/packages/vite/src/node/ssr/__tests__/ssrTransform.spec.ts b/packages/vite/src/node/ssr/__tests__/ssrTransform.spec.ts index 74ff0e5277c135..91554dfd34299f 100644 --- a/packages/vite/src/node/ssr/__tests__/ssrTransform.spec.ts +++ b/packages/vite/src/node/ssr/__tests__/ssrTransform.spec.ts @@ -812,3 +812,33 @@ function test() { }" `) }) + +// #11806 +test('track scope by blocks', async () => { + expect( + await ssrTransformSimpleCode(` +import { foo, bar, baz } from 'foobar' +function test() { + [foo]; + { + let foo = 10; + let bar = 10; + } + try {} catch (baz){ baz }; + return bar; +}`), + ).toMatchInlineSnapshot(` + " + const __vite_ssr_import_0__ = await __vite_ssr_import__(\\"foobar\\"); + + function test() { + [__vite_ssr_import_0__.foo]; + { + let foo = 10; + let bar = 10; + } + try {} catch (baz){ baz }; + return __vite_ssr_import_0__.bar; + }" + `) +}) diff --git a/packages/vite/src/node/ssr/ssrTransform.ts b/packages/vite/src/node/ssr/ssrTransform.ts index b963494b7ab0b0..5fe2272d7fa4f7 100644 --- a/packages/vite/src/node/ssr/ssrTransform.ts +++ b/packages/vite/src/node/ssr/ssrTransform.ts @@ -448,6 +448,8 @@ function walk( if (parentFunction) { handlePattern(node.id, parentFunction) } + } else if (node.type === 'CatchClause' && node.param) { + handlePattern(node.param, node) } }, @@ -550,14 +552,14 @@ function isFunction(node: _Node): node is FunctionNode { return functionNodeTypeRE.test(node.type) } -const scopeNodeTypeRE = - /(?:Function|Class)(?:Expression|Declaration)$|Method$|^IfStatement$/ function findParentScope( parentStack: _Node[], isVar = false, ): _Node | undefined { - const regex = isVar ? functionNodeTypeRE : scopeNodeTypeRE - return parentStack.find((i) => regex.test(i.type)) + const predicate = isVar + ? isFunction + : (node: _Node) => node.type === 'BlockStatement' + return parentStack.find(predicate) } function isInDestructuringAssignment(