rsnext/server/render.js

52 lines
1.5 KiB
JavaScript
Raw Normal View History

2016-10-06 01:52:50 +02:00
import { relative, resolve } from 'path'
import { createElement } from 'react'
import { renderToString, renderToStaticMarkup } from 'react-dom/server'
import fs from 'mz/fs'
2016-10-08 12:16:22 +02:00
import Router from '../lib/router'
2016-10-06 01:52:50 +02:00
import Document from '../lib/document'
2016-10-07 03:57:31 +02:00
import Head from '../lib/head'
2016-10-06 01:52:50 +02:00
import App from '../lib/app'
2016-10-06 04:42:55 +02:00
import { StyleSheetServer } from '../lib/css'
2016-10-06 01:52:50 +02:00
2016-10-06 13:05:52 +02:00
export async function render (path, req, res, { dir = process.cwd(), dev = false } = {}) {
2016-10-08 12:16:22 +02:00
const mod = require(resolve(dir, '.next', 'pages', path))
const Component = mod.default || mod
2016-10-06 01:52:50 +02:00
let props = {}
if (Component.getInitialProps) {
props = await Component.getInitialProps({ req, res })
}
2016-10-06 13:05:52 +02:00
const bundlePath = resolve(dir, '.next', '_bundles', 'pages', (path || 'index') + '.js')
2016-10-06 01:52:50 +02:00
const component = await fs.readFile(bundlePath, 'utf8')
2016-10-06 04:42:55 +02:00
const { html, css } = StyleSheetServer.renderStatic(() => {
const app = createElement(App, {
Component,
props,
2016-10-08 12:16:22 +02:00
router: new Router(req.url)
2016-10-06 04:42:55 +02:00
})
return renderToString(app)
2016-10-06 01:52:50 +02:00
})
2016-10-07 03:57:31 +02:00
const head = Head.rewind() || []
2016-10-06 01:52:50 +02:00
const doc = createElement(Document, {
2016-10-07 03:57:31 +02:00
html,
head,
css,
2016-10-08 07:12:51 +02:00
data: { component, props },
2016-10-06 13:05:52 +02:00
hotReload: false,
dev
2016-10-06 01:52:50 +02:00
})
return '<!DOCTYPE html>' + renderToStaticMarkup(doc)
}
2016-10-06 13:05:52 +02:00
export async function renderJSON (path, { dir = process.cwd() }) {
const bundlePath = resolve(dir, '.next', '_bundles', 'pages', (path || 'index') + '.js')
2016-10-06 09:06:55 +02:00
const component = await fs.readFile(bundlePath, 'utf8')
return { component }
2016-10-06 01:52:50 +02:00
}