Last active
April 19, 2021 15:10
-
-
Save alexanderson1993/d75444f026ed8344aefa6700ba426430 to your computer and use it in GitHub Desktop.
Deno React SSR
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { | |
React, | |
ReactDOM, | |
} from "https://unpkg.com/es-react"; | |
import App from './app.tsx'; | |
ReactDOM.hydrate( | |
<App />, | |
document.body | |
); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { serve } from "https://deno.land/[email protected]/http/server.ts"; | |
import { posix } from "https://deno.land/[email protected]/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