1 Star 0 Fork 1

小太阳爸爸/vue_ssr

forked from 浊纹/vue_ssr 
加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
server.js 1.86 KB
一键复制 编辑 原始数据 按行查看 历史
浊纹 提交于 2024-04-18 16:00 . 版本升级
import fs from 'node:fs/promises'
import path from 'path'
import express from 'express'
const isProduction = process.env.NODE_ENV === 'production'
const port = process.env.PORT || 5173
const base = process.env.BASE || '/'
const resolve = (p) => path.resolve(p)
const templateHtml = isProduction
? await fs.readFile(resolve('dist/client/index.html'), 'utf-8')
: ''
const ssrManifest = isProduction
? await fs.readFile(resolve('dist/client/.vite/ssr-manifest.json'), 'utf-8')
: undefined
const app = express()
let vite
if (!isProduction) {
const { createServer } = await import('vite')
vite = await createServer({
server: { middlewareMode: true },
appType: 'custom',
base
})
app.use(vite.middlewares)
} else {
const compression = (await import('compression')).default
const sirv = (await import('sirv')).default
app.use(compression())
app.use(base, sirv('./dist/client', { extensions: [] }))
}
app.use('*', async (req, res) => {
try {
const url = req.originalUrl
let template
let render
if (!isProduction) {
template = await fs.readFile(resolve('index.html'), 'utf-8')
template = await vite.transformIndexHtml(url, template)
render = (await vite.ssrLoadModule('/src/ssr/entry-server.js')).render
} else {
template = templateHtml
render = (await import('./dist/server/entry-server.js')).render
}
const rendered = await render(url, ssrManifest)
const html = template
.replace(`<!--app-head-->`, rendered.head ?? '')
.replace(`<!--app-html-->`, rendered.html ?? '')
.replace(`<!--app-title-->`, rendered.title)
res.status(200).set({ 'Content-Type': 'text/html' }).send(html)
} catch (e) {
vite?.ssrFixStacktrace(e)
console.log(e)
res.status(500).end(e)
}
})
// Start http server
app.listen(port, () => {
console.log(`Server started at http://localhost:${port}`)
})
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
TypeScript
1
https://gitee.com/leyar/vue_ssr.git
[email protected]:leyar/vue_ssr.git
leyar
vue_ssr
vue_ssr
master

搜索帮助