Blog

Running Make when files are changed


Following up our post on 'Making websites with Make: a comparison of build tools', how do we get Make to automatically rebuild our project when files are changed?

We could use an NPM package like onchange or nodemon inside a shell or NPM script, but these feel laggy. We're running Linux exclusively, so we just use inotifywait:

#!/bin/sh
while true; do
  out=$(inotifywait -r -e modify -e create -e delete -e move package.json src/);
  if echo $out | grep 'DELETE\|MOVE'; then
    make clean;
  fi
  make all;
done

This runs make clean, forcing a complete rebuild when a source file or directory is moved or deleted, otherwise those changes wouldn't be fully reflected. Since these operations are relatively rare, we're not worried about the time cost of a complete rebuild, If we were, we could extract file and path information from the inotifywait output and pass that as a parameter to make clean, allowing us to apply selective deletion from within the Makefile.

If we needed portability, we'd probably use fswatch which wraps Linux, macOS, *BSD and Windows event monitors.


By Spritely Design