forked from vercel/next.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
render.js
76 lines (64 loc) · 1.95 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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import { join } from 'path'
import { parse } from 'url'
import { createElement } from 'react'
import { renderToString, renderToStaticMarkup } from 'react-dom/server'
import requireModule from './require'
import read from './read'
import Router from '../lib/router'
import Document from '../lib/document'
import Head from '../lib/head'
import App from '../lib/app'
import { renderStatic } from 'glamor/server'
export async function render (url, ctx = {}, {
dir = process.cwd(),
dev = false,
staticMarkup = false
} = {}) {
const path = getPath(url)
const mod = await requireModule(join(dir, '.next', 'dist', 'pages', path))
const Component = mod.default || mod
const props = await (Component.getInitialProps ? Component.getInitialProps(ctx) : {})
const component = await read(join(dir, '.next', 'bundles', 'pages', path))
const { html, css, ids } = renderStatic(() => {
const app = createElement(App, {
Component,
props,
router: new Router(ctx.req ? ctx.req.url : url)
})
return (staticMarkup ? renderToStaticMarkup : renderToString)(app)
})
const head = Head.rewind() || []
const doc = createElement(Document, {
html,
head,
css,
data: {
component,
props,
ids: ids,
err: ctx.err ? errorToJSON(ctx.err) : null
},
hotReload: false,
dev,
staticMarkup
})
return '<!DOCTYPE html>' + renderToStaticMarkup(doc)
}
export async function renderJSON (url, { dir = process.cwd() } = {}) {
const path = getPath(url)
const component = await read(join(dir, '.next', 'bundles', 'pages', path))
return { component }
}
export function errorToJSON (err) {
const { name, message, stack } = err
const json = { name, message, stack }
if (name === 'ModuleBuildError') {
// webpack compilation error
const { module: { rawRequest } } = err
json.module = { rawRequest }
}
return json
}
function getPath (url) {
return parse(url || '/').pathname.replace(/\.json$/, '')
}