Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

SWC vs Babel in Vite #72

Open
saolof opened this issue Jan 24, 2023 · 4 comments
Open

SWC vs Babel in Vite #72

saolof opened this issue Jan 24, 2023 · 4 comments

Comments

@saolof
Copy link

saolof commented Jan 24, 2023

Vite 4.0 has built-in support for SWC and supports using it for react project, and Vercel is pushing Turbopack which is also based on SWC with no Babel. Should this project support SWC to be forward compatible with new build tools?

@saolof saolof changed the title SWT vs Babel in Vite SWC vs Babel in Vite Jan 24, 2023
@frammiie
Copy link

Would love to see SWC support in the future for this preset 🙏

@rschristian
Copy link
Member

Please don't "bump" issues, it has absolutely no positive effect.

If someone wants to contribute something, we'll consider it, but right now the team doesn't have the resources to invest into such a thing.

@mochaaP
Copy link

mochaaP commented Jan 26, 2025

here's a patch for https://github.com/vitejs/vite-plugin-react-swc if anyone's interested in maintaining a fork, since upstream explicitly rejected this: vitejs/vite-plugin-react-swc#258

note that createContext memorization is missing (@swc/plugin-prefresh crashes for me.), but otherwise it works well.

diff --git a/package.json b/package.json
index 6b8e036..0b3dce7 100644
--- a/package.json
+++ b/package.json
@@ -17,7 +17,9 @@
     "@swc/core": "^1.7.26"
   },
   "peerDependencies": {
-    "vite": "^4 || ^5 || ^6"
+    "vite": "^4 || ^5 || ^6",
+    "@prefresh/core": "^1.5.3",
+    "@prefresh/utils": "^1.2.0"
   },
   "devDependencies": {
     "@arnaud-barre/tnode": "^0.19.2",
diff --git a/src/index.ts b/src/index.ts
index 7ee93d3..9359103 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -12,10 +12,11 @@ import {
 import { PluginOption, UserConfig, BuildOptions } from "vite";
 import { createRequire } from "module";
 
-const runtimePublicPath = "/@react-refresh";
+const runtimePublicPrefix = "/@vite-prefresh/";
+const prefreshCorePublicPath = runtimePublicPrefix + "core";
+const prefreshUtilsPublicPath = runtimePublicPrefix + "utils";
 
-const preambleCode = `import { injectIntoGlobalHook } from "__PATH__";
-injectIntoGlobalHook(window);
+const preambleCode = `import "__VITE_PREFRESH_CORE__"; import { flush as flushUpdates } from "__VITE_PREFRESH_UTILS__";
 window.$RefreshReg$ = () => {};
 window.$RefreshSig$ = () => (type) => type;`;
 
@@ -65,7 +66,7 @@ const isWebContainer = globalThis.process?.versions?.webcontainer;
 const react = (_options?: Options): PluginOption[] => {
   let hmrDisabled = false;
   const options = {
-    jsxImportSource: _options?.jsxImportSource ?? "react",
+    jsxImportSource: _options?.jsxImportSource ?? "preact",
     tsDecorators: _options?.tsDecorators,
     plugins: _options?.plugins
       ? _options?.plugins.map((el): typeof el => [resolve(el[0]), el[1]])
@@ -78,12 +79,14 @@ const react = (_options?: Options): PluginOption[] => {
     {
       name: "vite:react-swc:resolve-runtime",
       apply: "serve",
-      enforce: "pre", // Run before Vite default resolve to avoid syscalls
-      resolveId: (id) => (id === runtimePublicPath ? id : undefined),
-      load: (id) =>
-        id === runtimePublicPath
-          ? readFileSync(join(_dirname, "refresh-runtime.js"), "utf-8")
-          : undefined,
+      config: () => ({
+        resolve: {
+          alias: {
+            '/@vite-prefresh/core': import.meta.resolve('@prefresh/core'),
+            '/@vite-prefresh/utils': import.meta.resolve('@prefresh/utils'),
+          },
+        }
+      }),
     },
     {
       name: "vite:react-swc",
@@ -120,8 +123,11 @@ const react = (_options?: Options): PluginOption[] => {
           tag: "script",
           attrs: { type: "module" },
           children: preambleCode.replace(
-            "__PATH__",
-            config.server!.config.base + runtimePublicPath.slice(1),
+            "__VITE_PREFRESH_CORE__",
+            config.server!.config.base + prefreshCorePublicPath.slice(1),
+          ).replace(
+            "__VITE_PREFRESH_UTILS__",
+            config.server!.config.base + prefreshUtilsPublicPath.slice(1),
           ),
         },
       ],
@@ -150,7 +156,7 @@ const react = (_options?: Options): PluginOption[] => {
         const sourceMap: SourceMapPayload = JSON.parse(result.map!);
         sourceMap.mappings = ";;" + sourceMap.mappings;
 
-        result.code = `import * as RefreshRuntime from "${runtimePublicPath}";
+        result.code = `import "${prefreshCorePublicPath}"; import { flush as flushUpdates } from "${prefreshUtilsPublicPath}";
 
 ${result.code}`;
 
@@ -159,8 +165,8 @@ ${result.code}`;
           result.code = `if (!window.$RefreshReg$) throw new Error("React refresh preamble was not loaded. Something is wrong.");
 const prevRefreshReg = window.$RefreshReg$;
 const prevRefreshSig = window.$RefreshSig$;
-window.$RefreshReg$ = RefreshRuntime.getRefreshReg("${id}");
-window.$RefreshSig$ = RefreshRuntime.createSignatureFunctionForTransform;
+self.$RefreshReg$ = (type, id) => {self.__PREFRESH__.register(type, ${JSON.stringify(id)} + " " + id)};
+self.$RefreshSig$ = () => {let status = 'begin'; let savedType; return (type, key, forceReset, getCustomHooks) => { if (!savedType) savedType = type; status = self.__PREFRESH__.sign(type || savedType, key, forceReset, getCustomHooks, status); return type; }};
 
 ${result.code}
 
@@ -170,13 +176,12 @@ window.$RefreshSig$ = prevRefreshSig;
         }
 
         result.code += `
-RefreshRuntime.__hmr_import(import.meta.url).then((currentExports) => {
-  RefreshRuntime.registerExportsForReactRefresh("${id}", currentExports);
-  import.meta.hot.accept((nextExports) => {
-    if (!nextExports) return;
-    const invalidateMessage = RefreshRuntime.validateRefreshBoundaryAndEnqueueUpdate("${id}", currentExports, nextExports);
-    if (invalidateMessage) import.meta.hot.invalidate(invalidateMessage);
-  });
+import.meta.hot.accept((m) => {
+  try {
+    flushUpdates();
+  } catch (e) {
+    self.location.reload();
+  }
 });
 `;
 

@mochaaP
Copy link

mochaaP commented Jan 26, 2025

also cc @LingyuCoder, you might want to take a look at why this crashes swc:

 RAX  0x7fd540000ac0 ◂— 0
 RBX  0x7fdca6c03fc0 ◂— 0
 RCX  0
 RDX  0x322e3031
 RDI  0x7fd540000ac0 ◂— 0
 RSI  0x7fdca6bf74d2
 R8   0x7fd540000ac0 ◂— 0
 R9   0x7fdcac002fc0 —▸ 0x7fdcac002d68 ◂— 0x7fdcac002d68 /* 'h-' */
 R10  0
 R11  1
 R12  0x7fdca6bf74d2
 R13  0x322e3031
 R14  0x7fd540000ac0 ◂— 0
 R15  0x322e3031
 RBP  0x8000000000000000
*RSP  0x7fdcd1ff5ed0 ◂— 0x1d1ff5f68
*RIP  0x7fdcb9649dfc ◂— cmp r13, rbp

#0  __memcpy_avx_unaligned_erms () at ../sysdeps/x86_64/multiarch/memmove-vec-unaligned-erms.S:265
#1  0x00007fdcb9649dfc in ?? () from /home/mochaa/ghq/github.com/vitejs/vite-plugin-react-swc/node_modules/.pnpm/@[email protected]/node_modules/@swc/core-linux-x64-gnu/swc.linux-x64-gnu.node
#2  0x00007fdcb9644b45 in ?? () from /home/mochaa/ghq/github.com/vitejs/vite-plugin-react-swc/node_modules/.pnpm/@[email protected]/node_modules/@swc/core-linux-x64-gnu/swc.linux-x64-gnu.node
#3  0x00007fdcb9585610 in ?? () from /home/mochaa/ghq/github.com/vitejs/vite-plugin-react-swc/node_modules/.pnpm/@[email protected]/node_modules/@swc/core-linux-x64-gnu/swc.linux-x64-gnu.node
#4  0x00007fdcb95b0f58 in ?? () from /home/mochaa/ghq/github.com/vitejs/vite-plugin-react-swc/node_modules/.pnpm/@[email protected]/node_modules/@swc/core-linux-x64-gnu/swc.linux-x64-gnu.node
#5  0x00007fdcb957562e in ?? () from /home/mochaa/ghq/github.com/vitejs/vite-plugin-react-swc/node_modules/.pnpm/@[email protected]/node_modules/@swc/core-linux-x64-gnu/swc.linux-x64-gnu.node
#6  0x00007fdcb9536743 in ?? () from /home/mochaa/ghq/github.com/vitejs/vite-plugin-react-swc/node_modules/.pnpm/@[email protected]/node_modules/@swc/core-linux-x64-gnu/swc.linux-x64-gnu.node
#7  0x00007fdcb9537144 in ?? () from /home/mochaa/ghq/github.com/vitejs/vite-plugin-react-swc/node_modules/.pnpm/@[email protected]/node_modules/@swc/core-linux-x64-gnu/swc.linux-x64-gnu.node
#8  0x00007fdcb95b08c6 in ?? () from /home/mochaa/ghq/github.com/vitejs/vite-plugin-react-swc/node_modules/.pnpm/@[email protected]/node_modules/@swc/core-linux-x64-gnu/swc.linux-x64-gnu.node
#9  0x00007fdcb95b0a3f in ?? () from /home/mochaa/ghq/github.com/vitejs/vite-plugin-react-swc/node_modules/.pnpm/@[email protected]/node_modules/@swc/core-linux-x64-gnu/swc.linux-x64-gnu.node
#10 0x00007fdcb9486b9f in ?? () from /home/mochaa/ghq/github.com/vitejs/vite-plugin-react-swc/node_modules/.pnpm/@[email protected]/node_modules/@swc/core-linux-x64-gnu/swc.linux-x64-gnu.node
#11 0x00007fdcb9585edd in ?? () from /home/mochaa/ghq/github.com/vitejs/vite-plugin-react-swc/node_modules/.pnpm/@[email protected]/node_modules/@swc/core-linux-x64-gnu/swc.linux-x64-gnu.node
#12 0x00007fdcb9584b80 in ?? () from /home/mochaa/ghq/github.com/vitejs/vite-plugin-react-swc/node_modules/.pnpm/@[email protected]/node_modules/@swc/core-linux-x64-gnu/swc.linux-x64-gnu.node
#13 0x00007fdcb958496e in ?? () from /home/mochaa/ghq/github.com/vitejs/vite-plugin-react-swc/node_modules/.pnpm/@[email protected]/node_modules/@swc/core-linux-x64-gnu/swc.linux-x64-gnu.node
#14 0x00007fdcb941caa0 in ?? () from /home/mochaa/ghq/github.com/vitejs/vite-plugin-react-swc/node_modules/.pnpm/@[email protected]/node_modules/@swc/core-linux-x64-gnu/swc.linux-x64-gnu.node
#15 0x00007fdcb9422e6f in ?? () from /home/mochaa/ghq/github.com/vitejs/vite-plugin-react-swc/node_modules/.pnpm/@[email protected]/node_modules/@swc/core-linux-x64-gnu/swc.linux-x64-gnu.node
#16 0x00007fdcb941a3d2 in ?? () from /home/mochaa/ghq/github.com/vitejs/vite-plugin-react-swc/node_modules/.pnpm/@[email protected]/node_modules/@swc/core-linux-x64-gnu/swc.linux-x64-gnu.node
#17 0x00007fdcb9421856 in ?? () from /home/mochaa/ghq/github.com/vitejs/vite-plugin-react-swc/node_modules/.pnpm/@[email protected]/node_modules/@swc/core-linux-x64-gnu/swc.linux-x64-gnu.node
#18 0x00007fdcb9421dcf in ?? () from /home/mochaa/ghq/github.com/vitejs/vite-plugin-react-swc/node_modules/.pnpm/@[email protected]/node_modules/@swc/core-linux-x64-gnu/swc.linux-x64-gnu.node
#19 0x00007fdcb901c986 in ?? () from /home/mochaa/ghq/github.com/vitejs/vite-plugin-react-swc/node_modules/.pnpm/@[email protected]/node_modules/@swc/core-linux-x64-gnu/swc.linux-x64-gnu.node
#20 0x00007fdcb90bd4c7 in ?? () from /home/mochaa/ghq/github.com/vitejs/vite-plugin-react-swc/node_modules/.pnpm/@[email protected]/node_modules/@swc/core-linux-x64-gnu/swc.linux-x64-gnu.node
#21 0x00007fdcb90a35cc in ?? () from /home/mochaa/ghq/github.com/vitejs/vite-plugin-react-swc/node_modules/.pnpm/@[email protected]/node_modules/@swc/core-linux-x64-gnu/swc.linux-x64-gnu.node
#22 0x00007fdcb90be46c in ?? () from /home/mochaa/ghq/github.com/vitejs/vite-plugin-react-swc/node_modules/.pnpm/@[email protected]/node_modules/@swc/core-linux-x64-gnu/swc.linux-x64-gnu.node
#23 0x00007fdcb90f9c3e in ?? () from /home/mochaa/ghq/github.com/vitejs/vite-plugin-react-swc/node_modules/.pnpm/@[email protected]/node_modules/@swc/core-linux-x64-gnu/swc.linux-x64-gnu.node
#24 0x00007fdcb9047727 in ?? () from /home/mochaa/ghq/github.com/vitejs/vite-plugin-react-swc/node_modules/.pnpm/@[email protected]/node_modules/@swc/core-linux-x64-gnu/swc.linux-x64-gnu.node
#25 0x00007fdcdd1e8f27 in node::ThreadPoolWork::ScheduleWork()::{lambda(uv_work_s*)#1}::operator()(uv_work_s*) const () at ../../src/threadpoolwork-inl.h:44
#26 node::ThreadPoolWork::ScheduleWork()::{lambda(uv_work_s*)#1}::_FUN(uv_work_s*) () at ../../src/threadpoolwork-inl.h:47
#27 0x00007fdcdcde37ea in worker (arg=0x0) at /usr/src/debug/libuv-1.50.0-1.fc42.x86_64/src/threadpool.c:123
#28 0x00007fdcdce7e444 in start_thread (arg=<optimized out>) at pthread_create.c:448
#29 0x00007fdcdcf01dfc in __GI___clone3 () at ../sysdeps/unix/sysv/linux/x86_64/clone3.S:78

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants