11import fs from "fs" ;
22import path from "path" ;
3+ import { SourceMapPayload } from "module" ;
34import { transform } from "@swc/core" ;
45import { PluginOption } from "vite" ;
56
@@ -46,7 +47,7 @@ export const swcReactRefresh = (): PluginOption => ({
4647 filename : id ,
4748 swcrc : false ,
4849 configFile : false ,
49-
50+ sourceMaps : true ,
5051 jsc : {
5152 target : "es2020" ,
5253 transform : {
@@ -60,17 +61,20 @@ export const swcReactRefresh = (): PluginOption => ({
6061 } ,
6162 } ,
6263 } ) ;
64+ let mappingPrefix = "" ;
6365
6466 if (
6567 ! automaticRuntime &&
6668 result . code . includes ( "React.createElement" ) &&
6769 ! importReactRE . test ( result . code )
6870 ) {
6971 result . code = `import React from "react";\n${ result . code } ` ;
72+ mappingPrefix += ";" ;
7073 }
71- if ( ! result . code . includes ( "$RefreshReg$" ) ) return result ;
7274
73- const header = `import * as RefreshRuntime from "${ runtimePublicPath } ";
75+ if ( result . code . includes ( "$RefreshReg$" ) ) {
76+ mappingPrefix += ";;;;;;;;;;;;" ;
77+ result . code = `import * as RefreshRuntime from "${ runtimePublicPath } ";
7478
7579let prevRefreshReg;
7680let prevRefreshSig;
@@ -81,14 +85,20 @@ prevRefreshReg = window.$RefreshReg$;
8185prevRefreshSig = window.$RefreshSig$;
8286window.$RefreshReg$ = RefreshRuntime.getRefreshReg("${ id } ");
8387window.$RefreshSig$ = RefreshRuntime.createSignatureFunctionForTransform;
84- ` ;
8588
86- const footer = `
89+ ${ result . code }
90+
8791window.$RefreshReg$ = prevRefreshReg;
8892window.$RefreshSig$ = prevRefreshSig;
8993import.meta.hot.accept();
90- RefreshRuntime.enqueueUpdate();` ;
94+ RefreshRuntime.enqueueUpdate();
95+ ` ;
96+ }
97+
98+ if ( ! mappingPrefix ) return result ;
9199
92- return { code : `${ header } ${ result . code } ${ footer } ` , map : result . map } ;
100+ const sourceMap : SourceMapPayload = JSON . parse ( result . map ! ) ;
101+ sourceMap . mappings = mappingPrefix + sourceMap . mappings ;
102+ return { code : result . code , map : sourceMap } ;
93103 } ,
94104} ) ;
0 commit comments