Making a Markdown Blog Using Webpack

A Brief Background

When I started working on this site, my first hunch was to use that classic static website builder, Jekyll. It’s simplicity and tight github integration seemed great. However, there’s just one issue: it’s not easily integrated with Webpack and the rest of the modern front-end dev stack. In fact, it seems written for Ruby on Rails devs—but let’s save that for another post.

Shortly after starting to look beyond Jekyll, I started fiddling around with the html-webpack-plugin and realized: wait a minute I think I can make a perfectly suitable blog with just this.

Configuring Webpack

So if you’re not already familiar with webpack, it relies on a webpack.config.js (or whatever you wanna name it) file that usually takes a form along the lines of:

And a webpack.config.js (using pug for templates) that looks something like this:

const HtmlWebpackPlugin =require("html-webpack-plugin");
module.exports ={// ...
plugins:[newHtmlWebpackPlugin({// A string identifying where the template is located.// and optionally which webpack loaders to use.
template:"pug!templates/index.pug",// Do you wanna make some cache? $$$
cache:true,// Specifying that only the "main" bundle should be inserted.
chunks:["main"],// The contents of your <title></title> tag.
title:"The Main Page",// The location and source of your output file.
filename:"pages/index.html",}),],// ...};

Sounds pretty simple right? It’s deceptively simple. Like webpack itself, this plugin’s minimal API surface area is where its power lies—and also in its ability to receive (and potentially render) arbitrary options.

Arbitrary Options and Loops

The secret to making a blog from all this is is learning to combine two features of the html-webpack-plugin:

The above code should spit out 100 pages based on your pug template, each with a different <title></title> and filename.

That’s obviously pretty useless. However, by harnessing feature #2 from the list above, you can do some useful stuff.

Injecting Arbitrary HTML In A Template

Because html-webpack-plugin takes an plain Object as its input, you can add additional key/value pairs very easily using our above looping system. However, the nicest part of all is that this data is all available inside the template from the htmlWebpackPlugin.options object. (Along with a few others outlined in its documention).

So if I were to add the following changes to my makeHtmlConfig function:

Examples

Although there are a couple other things going on in the webpack configs for this project (such as a distinction between static pages and posts), the principles are basically the same as the above examples.

Written by Omar Delarosa who lives in Brooklyn and builds things using computers.