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): handle function expression name scoping #16563

Merged
merged 1 commit into from
May 1, 2024
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
22 changes: 22 additions & 0 deletions packages/vite/src/node/ssr/__tests__/ssrTransform.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -249,6 +249,28 @@ test('do not rewrite when function declaration is in scope', async () => {
expect(result?.deps).toEqual(['vue'])
})

// #16452
test('do not rewrite when function expression is in scope', async () => {
const result = await ssrTransformSimple(
`import {fn} from './vue';var a = function() { return function fn() { console.log(fn) } }`,
)
expect(result?.code).toMatchInlineSnapshot(`
"const __vite_ssr_import_0__ = await __vite_ssr_import__("./vue", {"importedNames":["fn"]});
var a = function() { return function fn() { console.log(fn) } }"
`)
})

// #16452
test('do not rewrite when function expression is in global scope', async () => {
const result = await ssrTransformSimple(
`import {fn} from './vue';foo(function fn(a = fn) { console.log(fn) })`,
)
expect(result?.code).toMatchInlineSnapshot(`
"const __vite_ssr_import_0__ = await __vite_ssr_import__("./vue", {"importedNames":["fn"]});
foo(function fn(a = fn) { console.log(fn) })"
`)
})

test('do not rewrite catch clause', async () => {
const result = await ssrTransformSimple(
`import {error} from './dependency';try {} catch(error) {}`,
Expand Down
5 changes: 5 additions & 0 deletions packages/vite/src/node/ssr/ssrTransform.ts
Original file line number Diff line number Diff line change
Expand Up @@ -442,6 +442,11 @@ function walk(
setScope(parentScope, node.id!.name)
}
}
// If it is a function expression, its name (if exist) could also be
// shadowing an import. So add its own name to the scope
if (node.type === 'FunctionExpression' && node.id) {
setScope(node, node.id.name)
}
// walk function expressions and add its arguments to known identifiers
// so that we don't prefix them
node.params.forEach((p) => {
Expand Down