Skip to content

Instantly share code, notes, and snippets.

@alexanderson1993
Last active April 19, 2021 15:10
Show Gist options
  • Save alexanderson1993/d75444f026ed8344aefa6700ba426430 to your computer and use it in GitHub Desktop.
Save alexanderson1993/d75444f026ed8344aefa6700ba426430 to your computer and use it in GitHub Desktop.
Deno React SSR
import {
React,
} from "https://unpkg.com/es-react";
declare global {
namespace JSX {
interface IntrinsicElements {
h1: any;
div: any;
h2: any;
}
}
}
const App = () => {
return <div><h1>Hello World 🦕</h1></div>;
};
export default App;
import {
React,
ReactDOM,
} from "https://unpkg.com/es-react";
import App from './app.tsx';
ReactDOM.hydrate(
<App />,
document.body
);
import { serve } from "https://deno.land/std@0.50.0/http/server.ts";
import { posix } from "https://deno.land/std@0.50.0/path/mod.ts";
import ReactDOMServer from "https://dev.jspm.io/react-dom/server";
import { React } from "https://unpkg.com/es-react";
import App from "./app.tsx";
const s = serve({ port: 8000 });
console.log('Visit http://localhost:8000');
for await (const req of s) {
let normalizedUrl = posix.normalize(req.url);
if (normalizedUrl === "/") {
// Serve the React app
const body = ReactDOMServer.renderToString(<App />);
req.respond({
body: `<html><head></head><body>${body}
<script type="module" src="/bundle.js"></script>
</body></html>`,
});
} else if (normalizedUrl === "/bundle.js") {
// Serve the client side code
const headers = new Headers();
headers.set("content-type", "application/javascript");
const [diagnostics, body] = await Deno.bundle(
"https://gist.githubusercontent.com/alexanderson1993/d75444f026ed8344aefa6700ba426430/raw/7b0236da14d2e717e5c67e91740d955309ae41ba/browser.tsx",
undefined,
{
lib: ["dom"],
},
);
if (diagnostics != null) {
console.log(diagnostics);
throw new Error("Error bundling browser bundle.");
}
req.respond({ body, headers });
} else {
req.respond({ body: "404" });
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment