2023-11-04 13:02:08 +00:00
|
|
|
import fs from 'fs'
|
|
|
|
import path from 'path'
|
|
|
|
|
|
|
|
import { fileURLToPath } from 'url'
|
|
|
|
|
|
|
|
import Koa from 'koa'
|
|
|
|
import koaConnect from 'koa-connect'
|
|
|
|
|
|
|
|
import { createServer as createViteServer } from 'vite'
|
|
|
|
|
|
|
|
const HOST_NAME = '127.0.0.1'
|
|
|
|
const APP_PORT = 1007
|
|
|
|
|
|
|
|
const __dirname = path.dirname(fileURLToPath(import.meta.url))
|
|
|
|
|
2023-11-05 07:13:40 +00:00
|
|
|
// Inject teleports in template
|
|
|
|
const injectTeleports = (html: string, teleports: string) => {
|
|
|
|
if (teleports) {
|
|
|
|
for (const [target, content] of Object.entries(teleports)) {
|
|
|
|
if (['head', 'body', 'html'].includes(target)) {
|
|
|
|
const replacement = `</${target}>`
|
|
|
|
html = html.replace(replacement, content + replacement)
|
|
|
|
} else {
|
|
|
|
const replacement = ` id="${target.replace('#', '')}">`
|
|
|
|
html = html.replace(replacement, replacement + content)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return html
|
|
|
|
}
|
|
|
|
|
2023-11-04 13:02:08 +00:00
|
|
|
;(async () => {
|
|
|
|
const app = new Koa()
|
|
|
|
|
|
|
|
const vite = await createViteServer({
|
2023-11-04 14:06:19 +00:00
|
|
|
server: { middlewareMode: true },
|
2023-11-05 07:13:40 +00:00
|
|
|
appType: 'spa',
|
2023-11-04 13:02:08 +00:00
|
|
|
})
|
|
|
|
|
|
|
|
app.use(koaConnect(vite.middlewares))
|
|
|
|
|
|
|
|
app.use(async (ctx) => {
|
|
|
|
try {
|
|
|
|
let template = fs.readFileSync(
|
|
|
|
path.resolve(__dirname, 'index.html'),
|
|
|
|
'utf-8'
|
|
|
|
)
|
|
|
|
|
|
|
|
template = await vite.transformIndexHtml(ctx.path, template)
|
|
|
|
|
|
|
|
const { render } = await vite.ssrLoadModule('/src/entry-server.ts')
|
|
|
|
|
2023-11-05 07:13:40 +00:00
|
|
|
const [renderedHtml, renderedPinia, renderedLinks, renderedTeleports] =
|
|
|
|
await render(ctx, {})
|
|
|
|
|
|
|
|
const injectedTeleportsHtml = injectTeleports(template, renderedTeleports)
|
2023-11-04 13:02:08 +00:00
|
|
|
|
2023-11-05 07:13:40 +00:00
|
|
|
const html = injectedTeleportsHtml
|
|
|
|
.replace('<!--preload-links-->', renderedLinks)
|
2023-11-04 13:02:08 +00:00
|
|
|
.replace('<!--ssr-outlet-->', renderedHtml)
|
2023-11-05 07:13:40 +00:00
|
|
|
.replace('__pinia', renderedPinia)
|
2023-11-04 13:02:08 +00:00
|
|
|
|
|
|
|
ctx.type = 'text/html'
|
|
|
|
ctx.body = html
|
|
|
|
} catch (e) {
|
2023-11-04 14:06:19 +00:00
|
|
|
vite && vite.ssrFixStacktrace(e as Error)
|
2023-11-04 13:02:08 +00:00
|
|
|
ctx.throw(500, e as Error)
|
|
|
|
}
|
|
|
|
})
|
|
|
|
|
|
|
|
app.listen(APP_PORT, () => {
|
|
|
|
console.log(`Server is listening in http://${HOST_NAME}:${APP_PORT}`)
|
|
|
|
})
|
|
|
|
})()
|