Pre-Rendering Content

In notebook:
Building Modern Web Apps
Created at:
2016-02-02
Updated:
2016-02-02
Tags:
libraries JavaScript React Ampersand Webpack backend
- Question: Is the dynamic html building part of HJS-Webpack?
- It is part of Webpack
Henrik wrote this plugin for webpack to do this (extracting the html)

Talks about "isomorphic" or "universal" JavaScript. If there's no dynamic part of the page why render it on the client-side?
And what if there are some dynamic parts on the page? You have to have a dynamic service on the service.
On the server side we don't have access to the browser environment (window, DOM)

If using the ampersand singleton app pattern we spun up a NodeJS server, this singleton "app" object would be shared amongst all users on the server.
We have to isolate these things on the server. It's easier on public dynamic data, like a product page and just add the user-specific data. We could pre-render everything we DO know about the page.

He's going to show how to do it. 
  // ****     webpack.config.js       ****
// ++++ 4. compile our JSX, ES6 code with Babel for NodeJS
require('babel/register')

var getConfig = require('hjs-webpack')
// ++++ 2. import React
var React = require('react')
// ++++ 3. require public page
var PublicPage = require('./src/pages/public') 

module.exports = getConfig({
    in: 'src/app/js',
    out: 'public'.
    clearBeforBuild: true,
    html: function (context) {
        // ++++ 1. add prerendered parts
        const publicPage = React.renderToString(React.createElement(PublicPage))
        
        return {
            // ++++ 5. add publicPage to be rendered
            'index.html': context.defaultTemplate({html: publicPage}),
            '200.html': context.defaultTemplate()
        }
    }
})
At ++++ 3. : The NodeJS server cannot run the JSX components, it just runs JavaScript.
We have to tell Babel, to compile our source code before NodeJS runs it. ( ++++ 4.)

At ++++ 1.: only external files run through Babel, so here we cannot use JSX. 
React has a ​renderToString​ method for getting our rendered html.
We first have require babel/register otherwise it would break.

Question: react.renderStaticMarkup would be cleaner?
- Yes but it would strip the element ids, so it would be harder later to dynamically update the DOM elements.

Now we have rendered page. React will take over once the page has finished downloading.