6

I would like to set up gulp to be able to do two things: 1) use watchify to monitor updates in files and automatically rebuild using browserify on changes, and 2) do an ad-hoc build once and exit.

#1 seems to be working fine, but I'm having trouble getting #2 to work. I type gulp build in the terminal and everything is bundled up just fine, but gulp doesn't exit or quit; it just sits there and I'm not brought back to the command line.

What am I doing wrong? Here's the entire gulpfile:

'use strict';

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

var b = watchify(browserify({
  cache: {},
  packageCache: {},
  entries: ['./app/app.js'],
  debug: true,
  transform: ['reactify']
}));

b.on('log', gutil.log);

var bundle = function() {
  return b.bundle()
    .pipe(source('bundle.js'))
    .pipe(gulp.dest('./dist'));
};

gulp.task('watch', function() {
  b.on('update', bundle);
});

gulp.task('build', function() {
  bundle();
});

gulp.task('default', ['watch', 'build']);

And here's the output in my terminal:

[11:14:42] Using gulpfile ~/Web Dev/event-calendar/gulpfile.js
[11:14:42] Starting 'build'...
[11:14:42] Finished 'build' after 4.28 ms
[11:14:45] 1657755 bytes written (2.99 seconds)

Gulp is still running after the log at 11:14:45 and doesn't jump back out to the terminal.

Kev H
  • 241
  • 2
  • 9
  • Not directly related to the question, but you could use https://github.com/ngryman/gulp-bro which requires much less boilerplate with the same performances than watchify. – ngryman Mar 06 '16 at 18:32

1 Answers1

6

.bundle() shouldn't be called on the watchify wrapper. The following fixed everything:

'use strict';

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

var b = function() {
  return browserify({
    cache: {},
    packageCache: {},
    entries: ['./app/app.js'],
    debug: true,
    transform: ['reactify']
  });
};

var w = watchify(b());

w.on('log', gutil.log);

var bundle = function(pkg) {
  return pkg.bundle()
    .pipe(source('bundle.js'))
    .pipe(gulp.dest('./dist'));
};

gulp.task('watch', function() {
  bundle(w);
  w.on('update', bundle.bind(null, w));
});

gulp.task('build', bundle.bind(null, b()));

gulp.task('default', ['watch']);
Kev H
  • 241
  • 2
  • 9
  • but you DO call .bundle on watchify with this solution with bundle(w), whats the difference? – kuzditomi Oct 24 '16 at 14:48
  • @TamásKüzdi the difference is that in the `build` task of this version, it does not call .bundle on watchify. Notice in the OP that there is no separate `w` (watchify bundler) and `b` (browserify bundler). – plong0 Apr 07 '17 at 16:59
  • @plong0 as I see it he calls .bundle on w, which is a watchify instance – szx Aug 09 '19 at 09:20