coffeescriptgulpbrowserifywatchify

Using gulp + browserify + watchify + coffeeify tries to retranspile javascript instead of coffeescript


When I browserify my coffeescript code the first time it runs fine. However, when I make a change to my source code and watchify tries to re-run the bundling, coffeeify seems to want to run coffeescript against my javascript - based on this error I get from gulp:

events.js:72
    throw er; // Unhandled 'error' event
          ^
SyntaxError: reserved word 'var' while parsing file: /Volumes/dev/app/frontend/editor/main.coffee

This is my Gulpfile:

var gulp = require('gulp');
var gutil = require('gulp-util');
var watchify = require('watchify');
var browserify = require('browserify');
var coffeeify = require('coffeeify');
var source = require('vinyl-source-stream');
var stringify = require('stringify');
var _ = require('underscore');

var browserifyOpts = {
  basedir: "./app/frontend/editor",
  debug: true,
  extensions: ['.coffee'],
  entries: ['./main.coffee']
};
var opts = _.extend({}, watchify.args, browserifyOpts);
var bundler = browserify(opts);
var watch = watchify(bundler);

watch.on('update', bundle);
watch.on('log', gutil.log);

function bundle() {

  var b = function() {
    return bundler
      .transform(stringify(['.html']))
      .transform('coffeeify')
      .bundle()
      .pipe(source('main.js'))
      .pipe(gulp.dest('app/assets/javascripts/bundles'));
  };

  return b();

}

gulp.task('default', ['browserify-main']);
gulp.task('browserify-main', bundle);

How can I make the bundling process work with watchify too?


Solution

  • Move your transforms outside of the bundle function:

    var bundler = browserify(opts);
    bundler.transform(stringify(['.html']))
    bundler.transform('coffeeify')
    var watch = watchify(bundler);
    
    watch.on('update', bundle);
    watch.on('log', gutil.log);
    
    function bundle() {
    
      var b = function() {
        return bundler
          .bundle()
          .pipe(source('main.js'))
          .pipe(gulp.dest('app/assets/javascripts/bundles'));
      };
    
      return b();
    
    }