Last Updated: February 25, 2016
·
3.156K
· andreypopp

Watch for changes and then rebuild source code using make

Usually tools like CoffeeScript or LessCSS have a command line option to watch source files for changes and trigger rebuild on that, but what if your tool doesn't support this functionality? Ok, we can use powerful make utility instead, I will show you how using a basic example with CoffeeScript compiler.

Create Makefile and define a rule to compile all .coffee files inside src dir into .js files inside lib dir.

SRC=$(wildcard src/*.coffee)
LIB=$(SRC:src/%.coffee=lib/%.js)

lib/%.js: src/%.coffee
  coffee $< > $@

coffee: $(LIB)

Now you can do make coffee and it will compile all you .coffee to corresponding .js. This rule assumes lib dir already exists, but you can add mkdir -p lib if you want to.

The last thing you need is another useful utility called watch. Use it with make like this:

watch -n 0.5 make coffee

This line executes make infinitely and so rebuilds changed (and only changed) files for you once a 0.5 seconds.

2 Responses
Add your response

UNIX FTW

over 1 year ago ·

watch is great (!) here is a solution for the nodejs fan-boys (like I am):

#!/usr/bin/env node

var fs = require('fs');
fs.watch(process.argv[2], function (fsWatch) {

    var spawn = require('child_process').spawn,
        pro  = spawn(process.argv[3], [process.argv[4]]);

    pro.stdout.on('data', function (data) {
        console.log('(log): ' + data);
    });

    pro.stderr.on('data', function (data) {
        console.log('(error): ' + data);
    });
});

use it like this:

$ ./watch.js text.txt make test
over 1 year ago ·