Skip to content

Commit

Permalink
fix(ssr): track for statements as block scope (#13021)
Browse files Browse the repository at this point in the history
  • Loading branch information
bluwy committed Apr 27, 2023
1 parent f749c3e commit 2f8502f
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 4 deletions.
35 changes: 35 additions & 0 deletions packages/vite/src/node/ssr/__tests__/ssrTransform.spec.ts
Expand Up @@ -869,3 +869,38 @@ function test() {
}"
`)
})

test('track scope in for loops', async () => {
expect(
await ssrTransformSimpleCode(`
import { test } from './test.js'
for (const test of tests) {
console.log(test)
}
for (let test = 0; test < 10; test++) {
console.log(test)
}
for (const test in tests) {
console.log(test)
}`),
).toMatchInlineSnapshot(`
"const __vite_ssr_import_0__ = await __vite_ssr_import__(\\"./test.js\\");
for (const test of tests) {
console.log(test)
}
for (let test = 0; test < 10; test++) {
console.log(test)
}
for (const test in tests) {
console.log(test)
}"
`)
})
10 changes: 6 additions & 4 deletions packages/vite/src/node/ssr/ssrTransform.ts
Expand Up @@ -561,14 +561,16 @@ function isFunction(node: _Node): node is FunctionNode {
return functionNodeTypeRE.test(node.type)
}

const blockNodeTypeRE = /^BlockStatement$|^For(?:In|Of)?Statement$/
function isBlock(node: _Node) {
return blockNodeTypeRE.test(node.type)
}

function findParentScope(
parentStack: _Node[],
isVar = false,
): _Node | undefined {
const predicate = isVar
? isFunction
: (node: _Node) => node.type === 'BlockStatement'
return parentStack.find(predicate)
return parentStack.find(isVar ? isFunction : isBlock)
}

function isInDestructuringAssignment(
Expand Down

0 comments on commit 2f8502f

Please sign in to comment.