Skip to content

nealgriffin/static-site-generator-webpack-plugin-mithril-example

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

3 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Example using mithril with static-site-generator-webpack-plugin

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:

Step 1 - Enable Mithril to render html as a string

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().

Step 2.

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.

About

Example of using mithril with static-site-generator-webpack-plugin

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published