Skip to content

Commit

Permalink
fix(ssr): ssrTransfrom with function declaration in scope, fix #4306
Browse files Browse the repository at this point in the history
  • Loading branch information
patak-dev committed Oct 21, 2021
1 parent ea0c221 commit bddae4a
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
26 changes: 26 additions & 0 deletions packages/vite/src/node/ssr/__tests__/ssrTransform.spec.ts
Expand Up @@ -175,6 +175,32 @@ test('do not rewrite method definition', async () => {
expect(result.deps).toEqual(['vue'])
})

test('do not rewrite when variable is in scope', async () => {
const result = await ssrTransform(
`import { fn } from 'vue';function A(){ const fn = () => {}; return { fn }; }`,
null,
null
)
expect(result.code).toMatchInlineSnapshot(`
"const __vite_ssr_import_0__ = await __vite_ssr_import__(\\"vue\\");
function A(){ const fn = () => {}; return { fn }; }"
`)
expect(result.deps).toEqual(['vue'])
})

test('do not rewrite when function declaration is in scope', async () => {
const result = await ssrTransform(
`import { fn } from 'vue';function A(){ function fn() {}; return { fn }; }`,
null,
null
)
expect(result.code).toMatchInlineSnapshot(`
"const __vite_ssr_import_0__ = await __vite_ssr_import__(\\"vue\\");
function A(){ function fn() {}; return { fn }; }"
`)
expect(result.deps).toEqual(['vue'])
})

test('do not rewrite catch clause', async () => {
const result = await ssrTransform(
`import {error} from './dependency';try {} catch(error) {}`,
Expand Down
8 changes: 8 additions & 0 deletions packages/vite/src/node/ssr/ssrTransform.ts
Expand Up @@ -302,6 +302,14 @@ function walk(
onIdentifier(node, parent!, parentStack)
}
} else if (isFunction(node)) {
// If it is a function declaration, it could be shadowing an import
// Add its name to the scope so it won't gets replaced
if (node.type === 'FunctionDeclaration') {
const parentFunction = findParentFunction(parentStack)
if (parentFunction) {
setScope(parentFunction, 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

0 comments on commit bddae4a

Please sign in to comment.