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

48 lines
1.3 KiB
JavaScript
Raw Normal View History

2016-10-05 23:52:50 +00:00
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 App from '../lib/app'
2016-10-06 02:42:55 +00:00
import { StyleSheetServer } from '../lib/css'
2016-10-05 23:52:50 +00:00
2016-10-06 11:05:52 +00:00
export async function render (path, req, res, { dir = process.cwd(), dev = false } = {}) {
const mod = require(resolve(dir, '.next', 'pages', path)) || {}
2016-10-05 23:52:50 +00:00
const Component = mod.default
let props = {}
if (Component.getInitialProps) {
props = await Component.getInitialProps({ req, res })
}
2016-10-06 11:05:52 +00:00
const bundlePath = resolve(dir, '.next', '_bundles', 'pages', (path || 'index') + '.js')
2016-10-05 23:52:50 +00:00
const component = await fs.readFile(bundlePath, 'utf8')
2016-10-06 02:42:55 +00:00
const { html, css } = StyleSheetServer.renderStatic(() => {
const app = createElement(App, {
Component,
props,
router: {}
})
return renderToString(app)
2016-10-05 23:52:50 +00:00
})
const doc = createElement(Document, {
head: [],
2016-10-06 02:42:55 +00:00
html: html,
css: css,
2016-10-05 23:52:50 +00:00
data: { component },
2016-10-06 11:05:52 +00:00
hotReload: false,
dev
2016-10-05 23:52:50 +00:00
})
return '<!DOCTYPE html>' + renderToStaticMarkup(doc)
}
2016-10-06 11:05:52 +00:00
export async function renderJSON (path, { dir = process.cwd() }) {
const bundlePath = resolve(dir, '.next', '_bundles', 'pages', (path || 'index') + '.js')
2016-10-06 07:06:55 +00:00
const component = await fs.readFile(bundlePath, 'utf8')
return { component }
2016-10-05 23:52:50 +00:00
}