javascriptjquerygulpbrowserifywatchify

Gulp - concat result of watchify with few JS files


I have a JS application which is used watchify.

So, I want to concat result of watchify command w/ some other javascripts files, which are tends to be global (jQuery and so on). Here is my Javascript watchify command.

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

var scriptsDir = './scripts';
var buildDir = './build';


function handleErrors() {
  var args = Array.prototype.slice.call(arguments);
  notify.onError({
    title: "Compile Error",
    message: "<%= error.message %>"
  }).apply(this, args);
  this.emit('end'); // Keep gulp from hanging on this task
}


function buildScript(file, watch) {
  var props = {entries: [scriptsDir + '/' + file]};
  var bundler = watch ? watchify(props) : browserify(props);
  bundler.transform(reactify);
  function rebundle() {
    var stream = bundler.bundle({debug: true});
    return stream.on('error', handleErrors)
    .pipe(source(file))
    .pipe(gulp.dest(buildDir + '/'));
  }
  bundler.on('update', function() {
    rebundle();
    gutil.log('Rebundle...');
  });
  return rebundle();
}


gulp.task('build', function() {
  return buildScript('main.js', false);
});


gulp.task('default', ['build'], function() {
  return buildScript('main.js', true);
});

Here is the task I use for appending javascript files.

return gulp.src([
  './bower_components/jquery/dist/jquery.min.js',
  './bower_components/redactor-wysiwyg/redactor/redactor.js',
  './build/main.js' // output of `gulp build`.
]).pipe(concat('application.js'))
  .pipe(gulp.dest('./public/'));

How can I concat these javascript files using one function buildScript?


Solution

  • The main key is that nodejs stream has a end event. So,

    function rebundle() {
      var stream = bundler.bundle({debug: true});
    
      stream.on('end', function() { gulp.start('everything_you_want') }); 
    
      return stream.on('error', handleErrors)
        .pipe(source(file))
        .pipe(gulp.dest(buildDir + '/'));
    }