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

feat: create vite-plugin-error-overlay #272

Merged
merged 17 commits into from
Apr 13, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions packages/error-overlay/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
# vite-plugin-error-overlay

Vite plugin to show client runtime error via builtin error overlay.

cf. https://github.com/vitejs/vite/pull/6274

## usage

```ts
import { defineConfig } from "vite";
import { vitePluginErrorOverlay } from "@hiogawa/vite-plugin-error-overlay";

export default defineConfig({
plugins: [vitePluginErrorOverlay()],
});
```
5 changes: 5 additions & 0 deletions packages/error-overlay/examples/basic/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# react ssr example

```sh
pnpm -C packages/error-overlay/examples/basic dev
```
15 changes: 15 additions & 0 deletions packages/error-overlay/examples/basic/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<!doctype html>
<html>
<head>
<meta charset="UTF-8" />
<title>vite-ssr-react</title>
<meta
name="viewport"
content="width=device-width, height=device-height, initial-scale=1.0"
/>
</head>
<body>
<div id="root"><!--@INJECT_SSR@--></div>
<script src="/src/entry-client.tsx" type="module"></script>
</body>
</html>
20 changes: 20 additions & 0 deletions packages/error-overlay/examples/basic/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
{
"name": "@hiogawa/vite-plugin-error-overlay-examples-react",
"private": true,
"type": "module",
"scripts": {
"dev": "vite dev",
"build": "vite build && vite build --ssr",
"preview": "vite preview"
},
"dependencies": {
"@hiogawa/vite-plugin-ssr-middleware": "latest",
"@hiogawa/vite-plugin-error-overlay": "latest",
"@types/react": "^18.2.66",
"@types/react-dom": "^18.2.22",
"@vitejs/plugin-react": "^4.2.1",
"react": "19.0.0-canary-4c12339ce-20240408",
"react-dom": "19.0.0-canary-4c12339ce-20240408",
"vite": "latest"
}
}
39 changes: 39 additions & 0 deletions packages/error-overlay/examples/basic/src/app.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import React from "react";

export function App() {
const [input, setInput] = React.useState("");
const [counter, setCounter] = React.useState(0);

return (
<div
style={{
display: "flex",
flexDirection: "column",
gap: "0.5rem",
maxWidth: "300px",
}}
>
<h2>Example</h2>
<div>{import.meta.env.SSR ? "Hey server!" : "Hi client!"}</div>
<div>Input {input}</div>
<input
value={input}
onChange={(e) => {
setInput(e.target.value);
}}
/>
<div>Counter: {counter}</div>
<div style={{ display: "flex", gap: "0.5rem" }}>
<button onClick={() => setCounter(counter - 1)}>-1</button>
<button onClick={() => setCounter(counter + 1)}>+1</button>
<button
onClick={() => {
throw new Error("boom!");
}}
>
boom!
</button>
</div>
</div>
);
}
8 changes: 8 additions & 0 deletions packages/error-overlay/examples/basic/src/entry-client.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { hydrateRoot } from "react-dom/client";
import { App } from "./app";

function main() {
hydrateRoot(document.getElementById("root")!, <App />);
}

main();
23 changes: 23 additions & 0 deletions packages/error-overlay/examples/basic/src/entry-server.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import fs from "node:fs";
import type http from "node:http";
import { renderToString } from "react-dom/server";
import type { ViteDevServer } from "vite";
import { App } from "./app";

export default async function handler(
req: http.IncomingMessage & { viteDevServer: ViteDevServer },
res: http.ServerResponse,
) {
let html: string;
if (import.meta.env.DEV) {
html = await fs.promises.readFile("./index.html", "utf-8");
html = await req.viteDevServer.transformIndexHtml("/", html);
} else {
html = await fs.promises.readFile("./dist/client/index.html", "utf-8");
}

const ssrHtml = renderToString(<App />);
html = html.replace("<!--@INJECT_SSR@-->", ssrHtml);

res.setHeader("content-type", "text/html").end(html);
}
8 changes: 8 additions & 0 deletions packages/error-overlay/examples/basic/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"extends": "../../../../tsconfig.base.json",
"include": ["src", "vite.config.ts"],
"compilerOptions": {
"types": ["vite/client"],
"jsx": "react-jsx"
}
}
19 changes: 19 additions & 0 deletions packages/error-overlay/examples/basic/vite.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { vitePluginErrorOverlay } from "@hiogawa/vite-plugin-error-overlay";
import {
vitePluginLogger,
vitePluginSsrMiddleware,
} from "@hiogawa/vite-plugin-ssr-middleware";
import react from "@vitejs/plugin-react";
import { defineConfig } from "vite";

export default defineConfig((_env) => ({
clearScreen: false,
plugins: [
react(),
vitePluginErrorOverlay(),
vitePluginLogger(),
vitePluginSsrMiddleware({
entry: "/src/entry-server.tsx",
}),
],
}));
30 changes: 30 additions & 0 deletions packages/error-overlay/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
{
"name": "@hiogawa/vite-plugin-error-overlay",
"version": "0.0.0",
"homepage": "https://github.com/hi-ogawa/vite-plugins/tree/main/packages/error-overlay",
"repository": {
"type": "git",
"url": "https://github.com/hi-ogawa/vite-plugins",
"directory": "packages/error-overlay"
},
"license": "MIT",
"type": "module",
"exports": {
".": {
"import": "./dist/index.js",
"types": "./dist/index.d.ts"
}
},
"files": [
"dist"
],
"scripts": {
"build": "tsup",
"dev": "tsup --watch",
"prepack": "tsup --clean",
"release": "pnpm publish --no-git-checks --access public"
},
"peerDependencies": {
"vite": "*"
}
}
69 changes: 69 additions & 0 deletions packages/error-overlay/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import { type Plugin, type WebSocketClient } from "vite";
import { name as packageName } from "../package.json";

const virtualName = "virtual:runtime-error-overlay";

export function vitePluginErrorOverlay(options?: {
filter?: (error: Error) => boolean;
}): Plugin {
return {
name: packageName,
apply: "serve",
transformIndexHtml() {
return [
{
tag: "script",
// TODO: base?
attrs: { type: "module", src: "/@id/__x00__" + virtualName },
},
];
},
resolveId(source, _importer, _options) {
return source === virtualName ? "\0" + virtualName : undefined;
},
load(id, _options) {
if (id === "\0" + virtualName) {
return `(${clientScriptFn.toString()})()`;
}
return;
},
configureServer(server) {
server.hot.on("custom:runtime-error", (...args: any[]) => {
const [data, client] = args as [unknown, WebSocketClient];
const error = Object.assign(new Error(), data);
if (options?.filter?.(error) ?? true) {
client.send({
type: "error",
err: {
message: error.message,
stack: error.stack ?? "", // TODO: solve sourcemap
},
});
}
});
},
};
}

function clientScriptFn() {
if (import.meta.hot) {
window.addEventListener("error", (evt) => {
sendError(evt.error);
});

window.addEventListener("unhandledrejection", (evt) => {
sendError(evt.reason);
});

function sendError(e: unknown) {
const error =
e instanceof Error ? e : new Error("(unknown error)", { cause: e });
const serialized = {
message: error.message,
stack: error.stack,
cause: error.cause,
};
import.meta.hot?.send("custom:runtime-error", serialized);
}
}
}
7 changes: 7 additions & 0 deletions packages/error-overlay/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"extends": "../../tsconfig.base.json",
"include": ["src"],
"compilerOptions": {
"types": ["vite/client"]
}
}
7 changes: 7 additions & 0 deletions packages/error-overlay/tsup.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { defineConfig } from "tsup";

export default defineConfig({
entry: ["src/index.ts"],
format: ["esm"],
dts: true,
});
33 changes: 33 additions & 0 deletions pnpm-lock.yaml

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