Skip to content

Commit 02db947

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

2 files changed

Lines changed: 27 additions & 0 deletions

File tree

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

Lines changed: 22 additions & 0 deletions
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+
constresult=awaitssrTransformSimple(
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+
constresult=awaitssrTransformSimple(
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
constresult=awaitssrTransformSimple(
254276
`import {error} from './dependency';try {} catch(error) {}`,

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

Lines changed: 5 additions & 0 deletions
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)