@@ -2,7 +2,7 @@ import fs from 'fs'
2
2
import path from 'path'
3
3
import { pathToFileURL } from 'url'
4
4
import { ViteDevServer } from '..'
5
- import { cleanUrl , resolveFrom , unwrapId } from '../utils'
5
+ import { dynamicImport , cleanUrl , isBuiltin , resolveFrom , unwrapId , usingDynamicImport } from '../utils'
6
6
import { rebindErrorStacktrace , ssrRewriteStacktrace } from './ssrStacktrace'
7
7
import {
8
8
ssrExportAllKey ,
@@ -95,12 +95,7 @@ async function instantiateModule(
95
95
96
96
const ssrImport = async ( dep : string ) => {
97
97
if ( dep [ 0 ] !== '.' && dep [ 0 ] !== '/' ) {
98
- return nodeRequire (
99
- dep ,
100
- mod . file ,
101
- server . config . root ,
102
- ! ! server . config . resolve . preserveSymlinks
103
- )
98
+ return nodeImport ( dep , mod . file , server . config )
104
99
}
105
100
dep = unwrapId ( dep )
106
101
if ( ! isCircular ( dep ) && ! pendingImports . get ( dep ) ?. some ( isCircular ) ) {
@@ -178,15 +173,29 @@ async function instantiateModule(
178
173
return Object . freeze ( ssrModule )
179
174
}
180
175
181
- function nodeRequire (
176
+ // In node@12+ we can use dynamic import to load CJS and ESM
177
+ async function nodeImport (
182
178
id : string ,
183
179
importer : string | null ,
184
- root : string ,
185
- preserveSymlinks : boolean
180
+ config : ViteDevServer [ 'config' ]
186
181
) {
187
- const mod = require ( resolve ( id , importer , root , preserveSymlinks ) )
188
- const defaultExport = mod . __esModule ? mod . default : mod
189
- // rollup-style default import interop for cjs
182
+ let url : string
183
+ // `resolve` doesn't handle `node:` builtins, so handle them directly
184
+ if ( id . startsWith ( 'node:' ) || isBuiltin ( id ) ) {
185
+ url = id
186
+ } else {
187
+ url = resolve ( id , importer , config . root , ! ! config . resolve . preserveSymlinks )
188
+ if ( usingDynamicImport ) {
189
+ url = pathToFileURL ( url ) . toString ( )
190
+ }
191
+ }
192
+ const mod = await dynamicImport ( url )
193
+ return proxyESM ( id , mod )
194
+ }
195
+
196
+ // rollup-style default import interop for cjs
197
+ function proxyESM ( id : string , mod : any ) {
198
+ const defaultExport = mod . __esModule ? mod . default : mod . default ? mod . default : mod
190
199
return new Proxy ( mod , {
191
200
get ( mod , prop ) {
192
201
if ( prop === 'default' ) return defaultExport
0 commit comments