diff --git a/CHANGELOG.md b/CHANGELOG.md index d6546bd..0eb60f0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,9 @@ # Changelog +## 2.1.0 + +Add source maps support + ## 2.0.3 Include `react/jsx-dev-runtime` for dependencies optimisation when using automatic runtime. diff --git a/package.json b/package.json index aa2e187..cbd6d0d 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "vite-plugin-swc-react-refresh", "description": "Use the versatility of swc for development and the maturity of esbuild for production", - "version": "2.0.3", + "version": "2.1.0", "license": "MIT", "author": "Arnaud Barré (https://github.com/ArnaudBarre)", "main": "src/swc-react-refresh.js", diff --git a/src/swc-react-refresh.ts b/src/swc-react-refresh.ts index b25b3e9..7880b25 100644 --- a/src/swc-react-refresh.ts +++ b/src/swc-react-refresh.ts @@ -1,5 +1,6 @@ import fs from "fs"; import path from "path"; +import { SourceMapPayload } from "module"; import { transform } from "@swc/core"; import { PluginOption } from "vite"; @@ -46,7 +47,7 @@ export const swcReactRefresh = (): PluginOption => ({ filename: id, swcrc: false, configFile: false, - + sourceMaps: true, jsc: { target: "es2020", transform: { @@ -60,6 +61,7 @@ export const swcReactRefresh = (): PluginOption => ({ }, }, }); + let mappingPrefix = ""; if ( !automaticRuntime && @@ -67,10 +69,12 @@ export const swcReactRefresh = (): PluginOption => ({ !importReactRE.test(result.code) ) { result.code = `import React from "react";\n${result.code}`; + mappingPrefix += ";"; } - if (!result.code.includes("$RefreshReg$")) return result; - const header = `import * as RefreshRuntime from "${runtimePublicPath}"; + if (result.code.includes("$RefreshReg$")) { + mappingPrefix += ";;;;;;;;;;;;"; + result.code = `import * as RefreshRuntime from "${runtimePublicPath}"; let prevRefreshReg; let prevRefreshSig; @@ -81,14 +85,20 @@ prevRefreshReg = window.$RefreshReg$; prevRefreshSig = window.$RefreshSig$; window.$RefreshReg$ = RefreshRuntime.getRefreshReg("${id}"); window.$RefreshSig$ = RefreshRuntime.createSignatureFunctionForTransform; -`; - const footer = ` +${result.code} + window.$RefreshReg$ = prevRefreshReg; window.$RefreshSig$ = prevRefreshSig; import.meta.hot.accept(); -RefreshRuntime.enqueueUpdate();`; +RefreshRuntime.enqueueUpdate(); +`; + } + + if (!mappingPrefix) return result; - return { code: `${header}${result.code}${footer}`, map: result.map }; + const sourceMap: SourceMapPayload = JSON.parse(result.map!); + sourceMap.mappings = mappingPrefix + sourceMap.mappings; + return { code: result.code, map: sourceMap }; }, });