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

WIP: vite-plugin-react-swc integration #9092

Draft
wants to merge 3 commits into
base: dev
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
5 changes: 5 additions & 0 deletions packages/remix-dev/package.json
Expand Up @@ -103,13 +103,15 @@
"strip-ansi": "^6.0.1",
"tiny-invariant": "^1.2.0",
"vite": "5.1.3",
"@vitejs/plugin-react-swc": "^3.6.0",
"wrangler": "^3.28.2"
},
"peerDependencies": {
"@remix-run/react": "^2.8.1",
"@remix-run/serve": "^2.8.1",
"typescript": "^5.1.0",
"vite": "^5.1.0",
"@vitejs/plugin-react-swc": "^3.6.0",
"wrangler": "^3.28.2"
},
"peerDependenciesMeta": {
Expand All @@ -122,6 +124,9 @@
"vite": {
"optional": true
},
"@vitejs/plugin-react-swc": {
"optional": true
},
"wrangler": {
"optional": true
}
Expand Down
110 changes: 5 additions & 105 deletions packages/remix-dev/vite/plugin.ts
Expand Up @@ -5,7 +5,7 @@ import { type BinaryLike, createHash } from "node:crypto";
import * as path from "node:path";
import * as url from "node:url";
import * as fse from "fs-extra";
import babel from "@babel/core";
import reactPlugin from "@vitejs/plugin-react-swc";
import {
type ServerBuild,
unstable_setDevServerHooks as setDevServerHooks,
Expand Down Expand Up @@ -601,7 +601,9 @@ let deepFreeze = (o: any) => {
return o;
};

export type RemixVitePlugin = (config?: VitePluginConfig) => Vite.Plugin[];
export type RemixVitePlugin = (
config?: VitePluginConfig
) => Vite.PluginOption[];
export const remixVitePlugin: RemixVitePlugin = (remixUserConfig = {}) => {
// Prevent mutations to the user config
remixUserConfig = deepFreeze(remixUserConfig);
Expand Down Expand Up @@ -1676,46 +1678,7 @@ export const remixVitePlugin: RemixVitePlugin = (remixUserConfig = {}) => {
].join("\n");
},
},
{
name: "remix-react-refresh-babel",
async transform(code, id, options) {
if (viteCommand !== "serve") return;
if (id.includes("/node_modules/")) return;

let [filepath] = id.split("?");
let extensionsRE = /\.(jsx?|tsx?|mdx?)$/;
if (!extensionsRE.test(filepath)) return;

let devRuntime = "react/jsx-dev-runtime";
let ssr = options?.ssr === true;
let isJSX = filepath.endsWith("x");
let useFastRefresh = !ssr && (isJSX || code.includes(devRuntime));
if (!useFastRefresh) return;

if (isClientRoute(id)) {
return { code: addRefreshWrapper(ctx.remixConfig, code, id) };
}

let result = await babel.transformAsync(code, {
filename: id,
sourceFileName: filepath,
parserOpts: {
sourceType: "module",
allowAwaitOutsideFunction: true,
},
plugins: [[require("react-refresh/babel"), { skipEnvCheck: true }]],
sourceMaps: true,
});
if (result === null) return;

code = result.code!;
let refreshContentRE = /\$Refresh(?:Reg|Sig)\$\(/;
if (refreshContentRE.test(code)) {
code = addRefreshWrapper(ctx.remixConfig, code, id);
}
return { code, map: result.map };
},
},
reactPlugin(),
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

😍

{
name: "remix-hmr-updates",
async handleHotUpdate({ server, file, modules, read }) {
Expand Down Expand Up @@ -1772,69 +1735,6 @@ function isEqualJson(v1: unknown, v2: unknown) {
return JSON.stringify(v1) === JSON.stringify(v2);
}

function addRefreshWrapper(
remixConfig: ResolvedVitePluginConfig,
code: string,
id: string
): string {
let route = getRoute(remixConfig, id);
let acceptExports =
route || isClientRoute(id)
? [
"clientAction",
"clientLoader",
"handle",
"meta",
"links",
"shouldRevalidate",
]
: [];
return (
REACT_REFRESH_HEADER.replaceAll("__SOURCE__", JSON.stringify(id)) +
code +
REACT_REFRESH_FOOTER.replaceAll("__SOURCE__", JSON.stringify(id))
.replaceAll("__ACCEPT_EXPORTS__", JSON.stringify(acceptExports))
.replaceAll("__ROUTE_ID__", JSON.stringify(route?.id))
);
}

const REACT_REFRESH_HEADER = `
import RefreshRuntime from "${hmrRuntimeId}";

const inWebWorker = typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope;
let prevRefreshReg;
let prevRefreshSig;

if (import.meta.hot && !inWebWorker) {
if (!window.__vite_plugin_react_preamble_installed__) {
throw new Error(
"Remix Vite plugin can't detect preamble. Something is wrong."
);
}

prevRefreshReg = window.$RefreshReg$;
prevRefreshSig = window.$RefreshSig$;
window.$RefreshReg$ = (type, id) => {
RefreshRuntime.register(type, __SOURCE__ + " " + id)
};
window.$RefreshSig$ = RefreshRuntime.createSignatureFunctionForTransform;
}`.replace(/\n+/g, "");

const REACT_REFRESH_FOOTER = `
if (import.meta.hot && !inWebWorker) {
window.$RefreshReg$ = prevRefreshReg;
window.$RefreshSig$ = prevRefreshSig;
RefreshRuntime.__hmr_import(import.meta.url).then((currentExports) => {
RefreshRuntime.registerExportsForReactRefresh(__SOURCE__, currentExports);
import.meta.hot.accept((nextExports) => {
if (!nextExports) return;
__ROUTE_ID__ && window.__remixRouteModuleUpdates.set(__ROUTE_ID__, nextExports);
const invalidateMessage = RefreshRuntime.validateRefreshBoundaryAndEnqueueUpdate(currentExports, nextExports, __ACCEPT_EXPORTS__);
if (invalidateMessage) import.meta.hot.invalidate(invalidateMessage);
});
});
}`;

function getRoute(
pluginConfig: ResolvedVitePluginConfig,
file: string
Expand Down
139 changes: 139 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.