Skip to content

Commit

Permalink
fix: SSR import in development can't resolve default import (fix vite…
Browse files Browse the repository at this point in the history
  • Loading branch information
brillout committed Dec 2, 2021
1 parent 08a1ec7 commit f9f611f
Showing 1 changed file with 24 additions and 7 deletions.
31 changes: 24 additions & 7 deletions packages/vite/src/node/ssr/ssrModuleLoader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -263,23 +263,40 @@ 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
return mod[prop] ?? defaultExport?.[prop]
}
})
}

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
}
}

0 comments on commit f9f611f

Please sign in to comment.