forked from vercel/next.js
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathrender.js
50 lines (41 loc) · 1.4 KB
/
render.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import { relative, resolve } from 'path'
import { createElement } from 'react'
import { renderToString, renderToStaticMarkup } from 'react-dom/server'
import fs from 'mz/fs'
import Document from '../lib/document'
import Head from '../lib/head'
import App from '../lib/app'
import { StyleSheetServer } from '../lib/css'
export async function render (path, req, res, { dir = process.cwd(), dev = false } = {}) {
const mod = require(resolve(dir, '.next', 'pages', path)) || {}
const Component = mod.default
let props = {}
if (Component.getInitialProps) {
props = await Component.getInitialProps({ req, res })
}
const bundlePath = resolve(dir, '.next', '_bundles', 'pages', (path || 'index') + '.js')
const component = await fs.readFile(bundlePath, 'utf8')
const { html, css } = StyleSheetServer.renderStatic(() => {
const app = createElement(App, {
Component,
props,
router: {}
})
return renderToString(app)
})
const head = Head.rewind() || []
const doc = createElement(Document, {
html,
head,
css,
data: { component, props },
hotReload: false,
dev
})
return '<!DOCTYPE html>' + renderToStaticMarkup(doc)
}
export async function renderJSON (path, { dir = process.cwd() }) {
const bundlePath = resolve(dir, '.next', '_bundles', 'pages', (path || 'index') + '.js')
const component = await fs.readFile(bundlePath, 'utf8')
return { component }
}