Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(ssr): track for statements as block scope #13021

Merged
merged 1 commit into from Apr 27, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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