Search code examples
javascriptwatchifybrfs

Command to watch and bundle using brfs without watchify


I'm trying to replicate the behavior of watchify with the brfs transform, but I need to use brfs directly because I want to avoid the additional code added to the script when using require with browserify/watchify. Using brfs directly simply replaces require(theFile) with its contents and nothing else.

Using this command to bundle the following code produces my intended result:

brfs main.js > bundle.js
// main.js
var fs = require('fs');
var templates = {
    'header': fs.readFileSync('app/templates/header.html', 'utf8'),
    'nav-menu': fs.readFileSync('app/templates/nav-menu.html', 'utf8')
};

How do I set something up to watch for changes and have brfs bundle the script again when something changes?


Solution

  • I consider this approach using the brfs programmatic api to be most proper. The only difference from the example we discussed in the js chat is that you need to use fs.createReadStream to pipe the file into brfs, rather than passing the filename directly to brfs as we were doing.

    var gulp = require('gulp');
    var brfs = require('brfs');
    var fs   = require('fs');
    
    // task without watch
    gulp.task('bundle-templates', function() {
      fs.createReadStream('main.js')
        .pipe(brfs())
        .pipe(fs.createWriteStream('bundle.js'))
      ;
    });
    
    // this runs the `bundle-templates` task before starting the watch (initial bundle)
    gulp.task('watch-templates', ['bundle-templates'], function() {
      // now watch the templates and the js file and rebundle on change
      gulp.watch([
        'templates/*.html',
        'main.js'
      ], ['bundle-templates']);
    });
    

    Now run this command and you're all set:

    gulp watch-templates
    

    gulp is not necessary here. You can recreate this using any task runner or by executing a node script directly. You can use gaze directly to watch the files, which is the same watcher that gulp is using for gulp.watch.