simple vite react ssr setup

This commit is contained in:
MapleLeaf
2021-12-31 10:51:06 -06:00
committed by Darius
parent 44bdfa0d8e
commit 66e4ebc250
9 changed files with 223 additions and 328 deletions

View File

@@ -0,0 +1,22 @@
{
"name": "reacord-docs-new",
"type": "module",
"private": true,
"scripts": {
"dev": "esmo src/server.tsx"
},
"dependencies": {
"express": "^4.17.2"
},
"devDependencies": {
"@types/express": "^4.17.13",
"@types/node": "*",
"@types/react": "^17.0.38",
"@types/react-dom": "^17.0.9",
"esno": "^0.13.0",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"typescript": "^4.5.4",
"vite": "^2.7.10"
}
}

View File

@@ -0,0 +1,11 @@
import * as React from "react"
export function Counter() {
const [count, setCount] = React.useState(0)
return (
<div>
<p>You clicked {count} times!</p>
<button onClick={() => setCount(count + 1)}>Click me</button>
</div>
)
}

View File

@@ -0,0 +1,5 @@
import * as React from "react"
import { render } from "react-dom"
import { Root } from "./root"
render(<Root />, document)

View File

@@ -0,0 +1,6 @@
import * as React from "react"
import { Root } from "./root"
export async function render(url: string) {
return <Root />
}

View File

@@ -0,0 +1,21 @@
import React from "react"
import { Counter } from "./counter"
export function Root() {
return (
<html lang="en">
<head>
<meta charSet="UTF-8" />
<meta httpEquiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="description" content="test description" />
<title>Reacord</title>
<script type="module" src="/src/entry.client.tsx" />
</head>
<body>
<h1>hi</h1>
<Counter />
</body>
</html>
)
}

View File

@@ -0,0 +1,35 @@
import express from "express"
import { renderToStaticMarkup } from "react-dom/server"
import { createServer as createViteServer } from "vite"
import type * as entryModule from "./entry.server"
const vite = await createViteServer({
server: { middlewareMode: "ssr" },
})
const app = express()
app.use(vite.middlewares)
app.use("*", async (req, res) => {
const url = req.originalUrl
try {
const { render } = (await vite.ssrLoadModule(
"/src/entry.server.tsx",
)) as typeof entryModule
const content = renderToStaticMarkup(await render(url))
const html = await vite.transformIndexHtml(url, content)
res.status(200).set({ "Content-Type": "text/html" }).end(html)
} catch (error: any) {
vite.ssrFixStacktrace(error)
console.error(error)
res.status(500).end(error.message)
}
})
const port = process.env.PORT || 3000
app.listen(port, () => {
console.log(`listening on http://localhost:${port}`)
})

View File

@@ -0,0 +1,3 @@
{
"extends": "../../tsconfig.base.json"
}