Skip to content

Commit

Permalink
fix: add ssrRequire in ssrloadmodule
Browse files Browse the repository at this point in the history
  • Loading branch information
yuuangzhang committed Nov 1, 2021
1 parent 852c984 commit 544fe89
Showing 1 changed file with 9 additions and 20 deletions.
29 changes: 9 additions & 20 deletions packages/vite/src/node/ssr/ssrModuleLoader.ts
Expand Up @@ -121,6 +121,10 @@ async function instantiateModule(
}
return moduleGraph.urlToModuleMap.get(dep)?.ssrModule
}
const ssrRequire = (dep: string) => {
const { resolve, dirname } = path
return require(resolve(dirname(mod.file!), dep))
}

const ssrDynamicImport = (dep: string) => {
// #3087 dynamic import vars is ignored at rewrite import path,
Expand Down Expand Up @@ -150,6 +154,7 @@ async function instantiateModule(
const AsyncFunction = async function () {}.constructor as typeof Function
const initModule = new AsyncFunction(
`global`,
`require`,
ssrModuleExportsKey,
ssrImportMetaKey,
ssrImportKey,
Expand All @@ -159,6 +164,7 @@ async function instantiateModule(
)
await initModule(
context.global,
ssrRequire,
ssrModule,
ssrImportMeta,
ssrImport,
Expand Down Expand Up @@ -188,27 +194,10 @@ async function nodeImport(
importer: string | null,
config: ViteDevServer['config']
) {
let url: string
// `resolve` doesn't handle `node:` builtins, so handle them directly
if (id.startsWith('node:') || isBuiltin(id)) {
url = id
} else {
url = resolve(id, importer, config.root, !!config.resolve.preserveSymlinks)
if (usingDynamicImport) {
url = pathToFileURL(url).toString()
}
}
const mod = await dynamicImport(url)
return proxyESM(id, mod)
}
const mod = require(resolve(id, importer, root, preserveSymlinks))

// rollup-style default import interop for cjs
function proxyESM(id: string, mod: any) {
const defaultExport = mod.__esModule
? mod.default
: mod.default
? mod.default
: mod
const defaultExport = mod.__esModule ? mod.default : mod
// rollup-style default import interop for cjs
return new Proxy(mod, {
get(mod, prop) {
if (prop === 'default') return defaultExport
Expand Down

0 comments on commit 544fe89

Please sign in to comment.