- 初始化一个 vite-react 项目
在 index.html
中添加一行注释,供替换模版字符串使用
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/src/favicon.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vite App</title>
</head>
<body>
<div id="root">
<!-- APP_HTML -->
</div>
<script type="module" src="/src/main.jsx"></script>
</body>
</html>
在 src 下添加 server-entry.jsx
文件
import ReactDOMServer from "react-dom/server";
import { App } from "./App";
export function render(url, context) {
return ReactDOMServer.renderToString(<App />);
}
安装 express
yarn add express
server.js ```javascript const express = require(“express”); const fs = require(“fs”); const app = express();
const { createServer: createViteServer } = require(“vite”);
createViteServer({ server: { middlewareMode: “ssr”, // 启动 ssr }, }).then((vite) => { app.use(vite.middlewares); // vite 中间件
app.get(“*”, async (req, res) => { // 读取文件 let template = fs.readFileSync(“index.html”, “utf-8”); template = await vite.transformIndexHtml(req.url, template); // 获取渲染函数 const { render } = await vite.ssrLoadModule(“/src/server-entry.jsx”); // 渲染路由对应的 html const html = await render(req.url); // 替换字符串为 html 模版 const responseHtml = template.replace(““, html); res.set(“content-type”, “text/html”).send(responseHtml); });
app.listen(4000); }); ```
- 启动 node 服务