Nuxt/packages/nitro/src/runtime/server.ts

55 lines
1.3 KiB
TypeScript
Raw Normal View History

2020-11-01 23:17:44 +00:00
import { createRenderer } from 'vue-bundle-renderer'
import devalue from '@nuxt/devalue'
// @ts-ignore
import { renderToString } from '~renderer'
2020-11-01 23:17:44 +00:00
// @ts-ignore
import server from '~build/dist/server/server'
// @ts-ignore
import clientManifest from '~build/dist/server/client.manifest.json'
// @ts-ignore
import htmlTemplate from '~build/views/document.template.js'
const renderer = createRenderer(server, {
clientManifest,
renderToString
})
export async function render (url, ctx: any) {
2020-11-03 20:26:27 +00:00
const start = process.hrtime()
2020-11-02 00:31:43 +00:00
const ssrContext: any = {
2020-11-01 23:17:44 +00:00
url,
runtimeConfig: {
public: {},
private: {}
},
...ctx
2020-11-01 23:17:44 +00:00
}
const rendered = await renderer.renderToString(ssrContext)
const state = `<script>window.__NUXT__ = ${devalue(ssrContext.payload)}</script>`
2020-11-03 20:26:27 +00:00
const _html = `<div id="__nuxt">${rendered.html}</div>`
2020-11-01 23:17:44 +00:00
2020-11-03 20:26:27 +00:00
const html = htmlTemplate({
2020-11-01 23:17:44 +00:00
HTML_ATTRS: '',
HEAD_ATTRS: '',
BODY_ATTRS: '',
HEAD: rendered.renderResourceHints() + rendered.renderStyles(),
2020-11-03 20:26:27 +00:00
APP: _html + state + rendered.renderScripts()
2020-11-01 23:17:44 +00:00
})
2020-11-03 20:26:27 +00:00
const end = process.hrtime(start)
const time = ((end[0] * 1e9) + end[1]) / 1e6
return {
html,
status: 200,
headers: {
'Content-Type': 'text/html;charset=UTF-8',
'X-Nuxt-Coldstart': global._coldstart + 'ms',
'X-Nuxt-ResponseTime': time + 'ms'
}
}
2020-11-01 23:17:44 +00:00
}