@@ -33,6 +33,8 @@ export const ssrDynamicImportKey = `__vite_ssr_dynamic_import__`
33
33
export const ssrExportAllKey = `__vite_ssr_exportAll__`
34
34
export const ssrImportMetaKey = `__vite_ssr_import_meta__`
35
35
36
+ const hashbangRE = / ^ # ! .* \n /
37
+
36
38
export async function ssrTransform (
37
39
code : string ,
38
40
inMap : SourceMap | null ,
@@ -92,13 +94,16 @@ async function ssrTransformScript(
92
94
const idToImportMap = new Map < string , string > ( )
93
95
const declaredConst = new Set < string > ( )
94
96
97
+ // hoist at the start of the file, after the hashbang
98
+ const hoistIndex = code . match ( hashbangRE ) ?. [ 0 ] . length ?? 0
99
+
95
100
function defineImport ( source : string ) {
96
101
deps . add ( source )
97
102
const importId = `__vite_ssr_import_${ uid ++ } __`
98
103
// There will be an error if the module is called before it is imported,
99
104
// so the module import statement is hoisted to the top
100
105
s . appendLeft (
101
- 0 ,
106
+ hoistIndex ,
102
107
`const ${ importId } = await ${ ssrImportKey } (${ JSON . stringify ( source ) } );\n` ,
103
108
)
104
109
return importId
@@ -165,7 +170,7 @@ async function ssrTransformScript(
165
170
// hoist re-exports near the defined import so they are immediately exported
166
171
for ( const spec of node . specifiers ) {
167
172
defineExport (
168
- 0 ,
173
+ hoistIndex ,
169
174
spec . exported . name ,
170
175
`${ importId } .${ spec . local . name } ` ,
171
176
)
@@ -214,9 +219,9 @@ async function ssrTransformScript(
214
219
const importId = defineImport ( node . source . value as string )
215
220
// hoist re-exports near the defined import so they are immediately exported
216
221
if ( node . exported ) {
217
- defineExport ( 0 , node . exported . name , `${ importId } ` )
222
+ defineExport ( hoistIndex , node . exported . name , `${ importId } ` )
218
223
} else {
219
- s . appendLeft ( 0 , `${ ssrExportAllKey } (${ importId } );\n` )
224
+ s . appendLeft ( hoistIndex , `${ ssrExportAllKey } (${ importId } );\n` )
220
225
}
221
226
}
222
227
}
0 commit comments