1
0
Fork 0
mirror of https://github.com/terribleplan/next.js.git synced 2024-01-19 02:48:18 +00:00
next.js/server/render.js
Naoyuki Kanezawa e775721f34 Hot reload error page (#190)
* add detach-plugin

* detach-plugin: remove unused property

* watch-pages-plugin: replace _error.js when user defined one was added/removed

* dynamic-entry-plugin: delete cache

* fix HMR settings for _error.js

* render: pass error only on dev

* hot-reload: enable to hot-reload error page

* server: check if /_error has compilation errors

* webapck-dev-client: fix reloading /_error
2016-11-04 00:12:37 +09:00

79 lines
2 KiB
JavaScript

import { join } from 'path'
import { parse } from 'url'
import { createElement } from 'react'
import { renderToString, renderToStaticMarkup } from 'react-dom/server'
import { renderStatic } from 'glamor/server'
import requireModule from './require'
import read from './read'
import getConfig from './config'
import Router from '../lib/router'
import Document from '../lib/document'
import Head from '../lib/head'
import App from '../lib/app'
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 config = await getConfig(dir)
const doc = createElement(Document, {
html,
head,
css,
data: {
component,
props,
ids: ids,
err: (ctx.err && dev) ? errorToJSON(ctx.err) : null
},
dev,
staticMarkup,
cdn: config.cdn
})
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$/, '')
}