Tangible Bytes

A Web Developer’s Blog

Hugo and Webpack

Hugo - The world’s fastest framework for building websites is pretty awesome. It’s what I use to manage this site.

But much of the web development world has moved in the direction of JavaScript, npm, and Webpack.

So how can you run a Hugo website and manage the embedded JavaScript and CSS that are most commonly managed with npm and Webpack?

The Hugo Way

Hugo pipes can convert SASS to CSS and build JS without the need for any thirst party code.

You still use npm to manage dependencies but Hugo manages the build - which gives you live page reloads in dev and the only compiled files are generated to your public directory (so you don’t have compiled files messing up git history)

The JS build tool is ESBuild

It’s really fast and having a simple build process that integrates with the Hugo live reload features is really nice.

The downside is that it isn’t as fully features as Webpack and doesn’t have the same level of plugin support.

People running loads of JavaScript on their sites are most likely using a JavaScript site generator.

Using Hugo pipes is really simple and works well for me.

Webpack Managed Themes

JavaScript build support inside Hugo is relatively new so what many people seem to have is to manage a theme with Webpack.

The process is to run a npm build task to process SASS and JS - creating files in the assets directory which Hugo can include in the page.

The theme then ships the compiled assets for other people to use.

The downside of this is that if you want to edit the files you have to npm install and then run an npm build each time you want to see a change (no live reload), once you’ve started editing the sources it becomes annoying to have the compiled code in Git, and it’s tricky to use asset fingerprinting.

Live Reload with Webpack

If you need any of the more advanced features of webpack (or if you already know and love webpack) but still want a live reload whenever you change code - there is a way.

  • remove the compiled files from git
  • generate a json manifest
  • use Hugo’s data templates to read this data and link to the fingerprinted files
  • have Webpack watch for file changes and rebuild as needed

This is a really good post on Webpack with Hugo to manage assets for your static website

There are a couple of clever bits here

  • Webpack generates a manifest which Hugo treats as data to work out the filenames of the fingerprinted files
  • It loads CSS/JS files from the Webpack dev server in dev mode

This succeeds in having the full power of Webpack available and having live page updates during dev by using the Hugo dev server for Hugo content but the webpack-dev-server for CSS/JS.

The only downside is the complexity.

There is another approach here to Building a static site with Hugo and Webpack This uses Webpack in “watch” mode to auto-generate updated assets on demand.