From f9f611fe888fea8556222e7d349c36758e9bf5ca Mon Sep 17 00:00:00 2001 From: Romuald Brillout Date: Wed, 1 Dec 2021 17:49:24 +0100 Subject: [PATCH] fix: SSR import in development can't resolve default import (fix #5706) --- packages/vite/src/node/ssr/ssrModuleLoader.ts | 31 ++++++++++++++----- 1 file changed, 24 insertions(+), 7 deletions(-) diff --git a/packages/vite/src/node/ssr/ssrModuleLoader.ts b/packages/vite/src/node/ssr/ssrModuleLoader.ts index 07deb0a44c3a7c..e23998e1af9506 100644 --- a/packages/vite/src/node/ssr/ssrModuleLoader.ts +++ b/packages/vite/src/node/ssr/ssrModuleLoader.ts @@ -263,19 +263,15 @@ async function nodeImport( try { const mod = await dynamicImport(url) - return proxyESM(id, mod) + return proxyESM(mod) } finally { unhookNodeResolve() } } // rollup-style default import interop for cjs -function proxyESM(id: string, mod: any) { - const defaultExport = mod.__esModule - ? mod.default - : mod.default - ? mod.default - : mod +function proxyESM(mod: any) { + const defaultExport = getDefaultExport(mod) return new Proxy(mod, { get(mod, prop) { if (prop === 'default') return defaultExport @@ -283,3 +279,24 @@ function proxyESM(id: string, mod: any) { } }) } + +function getDefaultExport(mod: any) { + if (!('__esModule' in mod)) { + // === CJS === + return 'default' in mod ? mod.default : mod + } else { + // === ESM === + // Unlike CJS, an ESM module can have no default export, + // thus we start right away with `mod.default` instead of `mod`. + let defaultExport = mod.default + const visited = new WeakSet() + while ('__esModule' in defaultExport && 'default' in defaultExport) { + if (visited.has(defaultExport)) { + break + } + visited.add(defaultExport) + defaultExport = defaultExport.default + } + return defaultExport + } +}