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

63 lines
1.7 KiB
JavaScript
Raw Normal View History

import { resolve } from 'path'
2016-10-10 04:24:30 +00:00
import { parse } from 'url'
2016-10-05 23:52:50 +00:00
import { createElement } from 'react'
import { renderToString, renderToStaticMarkup } from 'react-dom/server'
2016-10-15 19:49:42 +00:00
import requireModule from './require'
2016-10-08 12:01:58 +00:00
import read from './read'
2016-10-08 10:16:22 +00:00
import Router from '../lib/router'
2016-10-05 23:52:50 +00:00
import Document from '../lib/document'
2016-10-07 01:57:31 +00:00
import Head from '../lib/head'
2016-10-05 23:52:50 +00:00
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-10 04:24:30 +00:00
export async function render (url, ctx = {}, {
dir = process.cwd(),
dev = false,
2016-10-15 19:49:42 +00:00
staticMarkup = false
2016-10-10 04:24:30 +00:00
} = {}) {
const path = getPath(url)
2016-10-17 03:55:09 +00:00
const mod = await requireModule(resolve(dir, '.next', 'dist', 'pages', path))
2016-10-08 10:16:22 +00:00
const Component = mod.default || mod
2016-10-05 23:52:50 +00:00
2016-10-09 09:25:38 +00:00
const props = await (Component.getInitialProps ? Component.getInitialProps(ctx) : {})
2016-10-17 03:55:09 +00:00
const component = await read(resolve(dir, '.next', 'bundles', 'pages', path))
2016-10-05 23:52:50 +00:00
2016-10-06 02:42:55 +00:00
const { html, css } = StyleSheetServer.renderStatic(() => {
const app = createElement(App, {
Component,
props,
2016-10-10 04:24:30 +00:00
router: new Router(ctx.req ? ctx.req.url : url)
2016-10-06 02:42:55 +00:00
})
2016-10-10 04:24:30 +00:00
return (staticMarkup ? renderToStaticMarkup : renderToString)(app)
2016-10-05 23:52:50 +00:00
})
2016-10-07 01:57:31 +00:00
const head = Head.rewind() || []
2016-10-05 23:52:50 +00:00
const doc = createElement(Document, {
2016-10-07 01:57:31 +00:00
html,
head,
css,
2016-10-09 09:50:41 +00:00
data: {
component,
props,
classNames: css.renderedClassNames
},
2016-10-06 11:05:52 +00:00
hotReload: false,
2016-10-10 04:24:30 +00:00
dev,
staticMarkup
2016-10-05 23:52:50 +00:00
})
return '<!DOCTYPE html>' + renderToStaticMarkup(doc)
}
2016-10-15 19:49:42 +00:00
export async function renderJSON (url, { dir = process.cwd() } = {}) {
2016-10-10 04:24:30 +00:00
const path = getPath(url)
2016-10-17 03:55:09 +00:00
const component = await read(resolve(dir, '.next', 'bundles', 'pages', path))
2016-10-06 07:06:55 +00:00
return { component }
2016-10-05 23:52:50 +00:00
}
2016-10-10 04:24:30 +00:00
function getPath (url) {
return parse(url || '/').pathname.slice(1).replace(/\.json$/, '')
}