Last active
April 12, 2017 04:13
-
-
Save jschr/f4705b20c54377fdffac8cb8ae4fe038 to your computer and use it in GitHub Desktop.
ssr function step1
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as React from 'react' | |
import { renderToString, renderToStaticMarkup } from 'react-dom/server' | |
import Template from './components/Template' | |
import App from './components/App' | |
// our simple ssr function accepts appProps and a webpackStats | |
// object provided by static-website-generator-webpack-plugin | |
export default function ssr({ webpackStats, appProps }) { | |
// fetch a list of all the assets created by the webpack compiler | |
const assets = Object.keys(webpackStats.compilation.assets) | |
// we have not implemented any styling so we currently | |
// only care about js files | |
const js = assets.filter(value => value.match(/\.js$/)) | |
// render the app's initial html, which will be provided to the | |
// react root element | |
const body = renderToString(<App {...appProps} /> | |
const templateProps = { | |
js, | |
body, | |
// the template component will inject a script that sets | |
// `window.ssr = ${props.ssr}` in order to initialize the | |
// React app in the browser | |
ssr: { | |
appProps | |
} | |
} | |
// the final html is the result of calling renderToStaticMarkup | |
// with our Template component | |
const html = ` | |
<!doctype html> | |
${renderToStaticMarkup(<Template {...templateProps} />)} | |
` | |
return html | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment