feat: add production entry & template

This commit is contained in:
endiliey 2018-08-08 00:45:12 +08:00
parent 4c36e71d1f
commit b079e48976
2 changed files with 55 additions and 0 deletions

34
lib/core/prodEntry.js Normal file
View file

@ -0,0 +1,34 @@
import React from 'react';
import {BrowserRouter, StaticRouter} from 'react-router-dom';
import ReactDOM from 'react-dom';
import ReactDOMServer from 'react-dom/server';
import App from './App';
import createHtml from './prodTemplate';
// Client side render (e.g: running in browser) to become single-page application (SPA)
if (typeof document !== 'undefined') {
ReactDOM.render(
<BrowserRouter>
<App />
</BrowserRouter>,
document.getElementById('app')
);
}
// Renderer for static-site-generator-webpack-plugin (async rendering via callbacks)
export default function render(locals, callback) {
const context = {};
const body = ReactDOMServer.renderToString(
<StaticRouter location={locals.path} context={context}>
<App />
</StaticRouter>
);
const html = createHtml({
title: locals.title,
body,
bundlejs: locals.bundlejs,
lang: locals.lang
});
callback(null, html);
}

21
lib/core/prodTemplate.js Normal file
View file

@ -0,0 +1,21 @@
/**
* Html
* This Html.js file acts as a template that we insert all our generated
* application code into before sending it to the client as regular HTML.
* Note we're returning a template string from this function.
*/
module.exports = function createHtml({title, body, bundlejs, lang}) {
return `
<!DOCTYPE html>
<html lang="${lang}">
<head>
<title>${title}</title>
</head>
<body>
<div id="app">${body}</div>
<script src="${bundlejs}"></script>
</body>
</html>
`;
};