From 5306632603fb5bb6d93f06e2412416394166e371 Mon Sep 17 00:00:00 2001 From: patak Date: Thu, 21 Oct 2021 23:17:50 +0200 Subject: [PATCH] fix(ssr): ssrTransfrom with function declaration in scope, fix #4306 (#5376) --- .../node/ssr/__tests__/ssrTransform.spec.ts | 26 +++++++++++++++++++ packages/vite/src/node/ssr/ssrTransform.ts | 8 ++++++ 2 files changed, 34 insertions(+) diff --git a/packages/vite/src/node/ssr/__tests__/ssrTransform.spec.ts b/packages/vite/src/node/ssr/__tests__/ssrTransform.spec.ts index df206c2dfe9da4..111b31b890c89e 100644 --- a/packages/vite/src/node/ssr/__tests__/ssrTransform.spec.ts +++ b/packages/vite/src/node/ssr/__tests__/ssrTransform.spec.ts @@ -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) {}`, diff --git a/packages/vite/src/node/ssr/ssrTransform.ts b/packages/vite/src/node/ssr/ssrTransform.ts index 12055d64892ddf..77754abc52f192 100644 --- a/packages/vite/src/node/ssr/ssrTransform.ts +++ b/packages/vite/src/node/ssr/ssrTransform.ts @@ -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 get 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) =>