Dark mode
ข้อควรรู้
- ค่าเริ่มต้นของ Client Side Rendering (CSR) คือการเริ่มต้นแอพพลิเคชันบนเบราว์เซอร์
วิธีการทำ Server-Side Rendering (SSR)
- กำหนดโครงสร้างประมาณนี้
my-vite-ssr/
├── src/
│ ├── App.vue
│ ├── entry-client.ts # Entry point สำหรับ client
│ ├── entry-server.ts # Entry point สำหรับ server
│ └── main.ts
├── index.html
└── server.js # Server script
- ที่ html กำหนด entry point ไปที่ entry-server.ts
html
<div id="app"><!--ssr-outlet--></div>
<script type="module" src="/src/entry-client.js"></script>
Condition Logic
ใช้ import.meta.env.SSR สำหรับ server only logic หรือ import.meta.env.CSR สำหรับ client only logic
ts
if (import.meta.env.SSR) {
// ... server only logic
}
if (!import.meta.env.CSR) {
// ... client only logic
}
Setup Dev Server
หมายถึงเวลา run dev
ts
import express from "express";
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { createServer as createViteServer } from "vite";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
async function createServer() {
const app = express();
// Create Vite server in middleware mode and configure the app type as
// 'custom', disabling Vite's own HTML serving logic so parent server
// can take control
const vite = await createViteServer({
server: { middlewareMode: true },
appType: "custom",
});
// Use vite's connect instance as middleware. If you use your own
// express router (express.Router()), you should use router.use
// When the server restarts (for example after the user modifies
// vite.config.js), `vite.middlewares` is still going to be the same
// reference (with a new internal stack of Vite and plugin-injected
// middlewares). The following is valid even after restarts.
app.use(vite.middlewares);
app.use("*", async (req, res) => {
// serve index.html - we will tackle this next
});
app.listen(5173);
}
createServer();
เปลี่ยนจาก vite เป็น node server
json
{
"scripts": {
"dev": "vite",
"dev": "node server.js"
}
}
Building for Production
json
{
"scripts": {
"dev": "node server.js",
"build:client": "vite build",
"build:server": "vite build --ssr"
}
}