How to set up gulp to bundle several files into one?

Steve Tomlin picture Steve Tomlin · Mar 5, 2016 · Viewed 14.1k times · Source

This seems like a very simple question, but spent the last 3 hours researching it, discovering it can be slow on every save on a new file if not using watchify.

This is my directory tree:

gulpfile.js
package.json

www/
  default.htm
     <script src="toBundleJsHere/file123.js"></script>

  toBundletheseJs/
    componentX/
       file1.js
    componentY/
       file2.js
    componentZ/
      file3.js

  toPutBundledJsHere/
      file123.js

Requirements. On every creation or save of a file within the folder toBundleTheseJs/ I want this file to be rebundled into toBundleJsHere/

What do I need to include in my package.json file?

And whats the minimum I need to write into my gulp file?

This should be as fast as possible so think I should be using browserify and watchify. I want to understand the minimum steps so using package manager like jspm is overkill a this point.

thanks

Answer

Eran Shabi picture Eran Shabi · Mar 5, 2016

First you should listen to changes in the desired dir:

watch(['toBundletheseJs/**/*.js'], function () {
        gulp.run('bundle-js');
    });

Then the bundle-js task should bundle your files. A recommended way is gulp-concat:

var concat = require('gulp-concat');
var gulp = require('gulp');

gulp.task('bundle-js', function() {
  return gulp.src('toBundletheseJs/**/*.js')
    .pipe(concat('file123.js'))
    .pipe(gulp.dest('./toPutBundledJsHere/'));
});