A repository showing how to use the Mithril library alongside webpack and static-site-generator-webpack-plugin to create server-rendered, static pages based loosely off of this issue. Using Mithril to generate the static pages is a little more challenging. I don't really know too much about Mithril, but it looks like it expects to be run from within the context of a browser, whereas here it is being run in the context of node's runtime. Here's what I did:
The original issue post has this code snippet:
import m from 'mithril';
import Landing from './landing';
import './styles/theme.scss';
m.render(document.body, m(Landing));
The problem with this code snippet, and what was tripping me up, was that this code expects to be executed within the context of an actual browser. However, this code is being executed from within the context of the node runtime. This comment was really helpful in understanding that.
In order to fix this, a quick trip to google for 'mithril server rendered' led to mithril-node-render library and this adjusted code snippet:
import m from 'mithril';
import render from 'mithril-node-render';
import Landing from './landing';
export default (locals, callback) => {
render(m('span', 'huhu')).then(function (html) {
callback(null, "<html><head><title>Nice</title></head><body><h1>" + html + "</h1></body></html>");
})
}
Nice, so now the call to render()
returns a promise which will we resolve with the html you'd like to render. This code doesn't actually work yet, because we need to give the plugin access to DOM methods it expects, namely window()
and document()
.
Following the thread of the issue comment posted by sillero, led to this webpack.config.js change...
const jsdom = require('jsdom');
const { JSDOM } = jsdom;
const dom = new JSDOM();
//.....
plugins: [
new webpack.ProvidePlugin({m: 'mithril'}),
new StaticSiteGeneratorPlugin({
entry: 'main',
paths: [
'/hello/',
'/world/'
],
locals: {
greet: 'Hello'
},
globals: {
window: dom.window,
document: dom.document,
},
})
],
The key was passing in the elements to the globals parameter.