归档.zip

    • 初始化一个 vite-react 项目

    index.html 中添加一行注释,供替换模版字符串使用

    1. <!DOCTYPE html>
    2. <html lang="en">
    3. <head>
    4. <meta charset="UTF-8" />
    5. <link rel="icon" type="image/svg+xml" href="/src/favicon.svg" />
    6. <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    7. <title>Vite App</title>
    8. </head>
    9. <body>
    10. <div id="root">
    11. <!-- APP_HTML -->
    12. </div>
    13. <script type="module" src="/src/main.jsx"></script>
    14. </body>
    15. </html>

    在 src 下添加 server-entry.jsx 文件

    1. import ReactDOMServer from "react-dom/server";
    2. import { App } from "./App";
    3. export function render(url, context) {
    4. return ReactDOMServer.renderToString(<App />);
    5. }
    • 安装 express

      1. 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 服务