|
@@ -4,11 +4,12 @@ import { fileURLToPath } from 'url'
|
|
|
import express from 'express'
|
|
|
import serverStatic from 'serve-static'
|
|
|
import { createServer as createViteServer } from 'vite'
|
|
|
+import ssrManifest from './dist/client/.vite/ssr-manifest.json' assert { type: "json" }
|
|
|
const isProd = process.env.NODE_ENV === 'production'
|
|
|
const __dirname = path.dirname(fileURLToPath(
|
|
|
import.meta.url))
|
|
|
-
|
|
|
async function createServer() {
|
|
|
+ console.log(process.env.NODE_ENV)
|
|
|
const app = express()
|
|
|
// 以中间件模式创建 Vite 应用,并将 appType 配置为 'custom'
|
|
|
// 这将禁用 Vite 自身的 HTML 服务逻辑
|
|
@@ -18,7 +19,6 @@ async function createServer() {
|
|
|
appType: 'custom'
|
|
|
})
|
|
|
if(!isProd){
|
|
|
-
|
|
|
// 使用 vite 的 Connect 实例作为中间件
|
|
|
// 如果你使用了自己的 express 路由(express.Router()),你应该使用 router.use
|
|
|
// 当服务器重启(例如用户修改了 vite.config.js 后),
|
|
@@ -35,6 +35,7 @@ async function createServer() {
|
|
|
const url = req.originalUrl
|
|
|
let template
|
|
|
let render
|
|
|
+ let html
|
|
|
try {
|
|
|
if(!isProd){
|
|
|
// 1. 读取 index.html
|
|
@@ -63,7 +64,7 @@ async function createServer() {
|
|
|
path.resolve(__dirname, 'dist/client/index.html'),
|
|
|
'utf-8',
|
|
|
)
|
|
|
- render = require('./dist/entry-server.ts').render
|
|
|
+ render = (await vite.ssrLoadModule('/src/entry-server.ts')).render
|
|
|
}
|
|
|
|
|
|
|
|
@@ -74,10 +75,20 @@ async function createServer() {
|
|
|
// 4. 渲染应用的 HTML。这假设 entry-server.js 导出的 `render`
|
|
|
// 函数调用了适当的 SSR 框架 API。
|
|
|
// 例如 ReactDOMServer.renderToString()
|
|
|
- const appHtml = await render(url)
|
|
|
-
|
|
|
- // 5. 注入渲染后的应用程序 HTML 到模板中。
|
|
|
- const html = template.replace(`<!--ssr-outlet-->`, appHtml)
|
|
|
+ const manifest = ssrManifest
|
|
|
+ if(!isProd){
|
|
|
+ const { appHtml, state } = await render(url,manifest)
|
|
|
+ // 5. 注入渲染后的应用程序 HTML 到模板中。
|
|
|
+ html = template
|
|
|
+ .replace(`<!--ssr-outlet-->`, appHtml)
|
|
|
+ .replace('\'<!--vuex-state-->\'', JSON.stringify(state))
|
|
|
+ }else{
|
|
|
+ const { appHtml, state,preloadLinks } = await render(url,manifest)
|
|
|
+ html = template
|
|
|
+ .replace(`<!--preload-links-->`, preloadLinks)
|
|
|
+ .replace(`<!--ssr-outlet-->`, appHtml)
|
|
|
+ .replace('\'<!--vuex-state-->\'', JSON.stringify(state))
|
|
|
+ }
|
|
|
|
|
|
// 6. 返回渲染后的 HTML。
|
|
|
res.status(200).set({ 'Content-Type': 'text/html' }).end(html)
|