Skip to content

Commit

Permalink
Add source maps support [publish]
Browse files Browse the repository at this point in the history
  • Loading branch information
ArnaudBarre committed Oct 22, 2022
1 parent 95291df commit a28b087
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 8 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -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.
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -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",
Expand Down
24 changes: 17 additions & 7 deletions src/swc-react-refresh.ts
Original file line number Diff line number Diff line change
@@ -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";

Expand Down Expand Up @@ -46,7 +47,7 @@ export const swcReactRefresh = (): PluginOption => ({
filename: id,
swcrc: false,
configFile: false,

sourceMaps: true,
jsc: {
target: "es2020",
transform: {
Expand All @@ -60,17 +61,20 @@ export const swcReactRefresh = (): PluginOption => ({
},
},
});
let mappingPrefix = "";

if (
!automaticRuntime &&
result.code.includes("React.createElement") &&
!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;
Expand All @@ -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 };
},
});

0 comments on commit a28b087

Please sign in to comment.