Skip to content

Commit

Permalink
fix: scope tracking for shadowing variables in blocks (#11806) (#11811)
Browse files Browse the repository at this point in the history
  • Loading branch information
gtm-nayan committed Jan 25, 2023
1 parent 4bbebf3 commit 568bdab
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 4 deletions.
30 changes: 30 additions & 0 deletions packages/vite/src/node/ssr/__tests__/ssrTransform.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}"
`)
})
10 changes: 6 additions & 4 deletions packages/vite/src/node/ssr/ssrTransform.ts
Original file line number Diff line number Diff line change
Expand Up @@ -448,6 +448,8 @@ function walk(
if (parentFunction) {
handlePattern(node.id, parentFunction)
}
} else if (node.type === 'CatchClause' && node.param) {
handlePattern(node.param, node)
}
},

Expand Down Expand Up @@ -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(
Expand Down

0 comments on commit 568bdab

Please sign in to comment.