Skip to content

Commit 02db947

Browse files
authored
fix(ssr): handle function expression name scoping (#16563)
1 parent 2f42006 commit 02db947

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
lines changed

packages/vite/src/node/ssr/__tests__/ssrTransform.spec.ts

+22
Original file line numberDiff line numberDiff line change
@@ -249,6 +249,28 @@ test('do not rewrite when function declaration is in scope', async () => {
249249
expect(result?.deps).toEqual(['vue'])
250250
})
251251

252+
// #16452
253+
test('do not rewrite when function expression is in scope', async () => {
254+
const result = await ssrTransformSimple(
255+
`import {fn} from './vue';var a = function() { return function fn() { console.log(fn) } }`,
256+
)
257+
expect(result?.code).toMatchInlineSnapshot(`
258+
"const __vite_ssr_import_0__ = await __vite_ssr_import__("./vue", {"importedNames":["fn"]});
259+
var a = function() { return function fn() { console.log(fn) } }"
260+
`)
261+
})
262+
263+
// #16452
264+
test('do not rewrite when function expression is in global scope', async () => {
265+
const result = await ssrTransformSimple(
266+
`import {fn} from './vue';foo(function fn(a = fn) { console.log(fn) })`,
267+
)
268+
expect(result?.code).toMatchInlineSnapshot(`
269+
"const __vite_ssr_import_0__ = await __vite_ssr_import__("./vue", {"importedNames":["fn"]});
270+
foo(function fn(a = fn) { console.log(fn) })"
271+
`)
272+
})
273+
252274
test('do not rewrite catch clause', async () => {
253275
const result = await ssrTransformSimple(
254276
`import {error} from './dependency';try {} catch(error) {}`,

packages/vite/src/node/ssr/ssrTransform.ts

+5
Original file line numberDiff line numberDiff line change
@@ -442,6 +442,11 @@ function walk(
442442
setScope(parentScope, node.id!.name)
443443
}
444444
}
445+
// If it is a function expression, its name (if exist) could also be
446+
// shadowing an import. So add its own name to the scope
447+
if (node.type === 'FunctionExpression' && node.id) {
448+
setScope(node, node.id.name)
449+
}
445450
// walk function expressions and add its arguments to known identifiers
446451
// so that we don't prefix them
447452
node.params.forEach((p) => {

0 commit comments

Comments
 (0)