Search code examples
javascriptnode.jsgulpbrowserifygulp-concat

Using Browserify on only a subset of files in a folder within a Gulp task


Typically with Browserify, if you want to combine a number of files, you run something like the following:

gulp.task('build-tests', function() {
    var b = browserify({
                entries: ['./lib/some_specs.js', './lib/some_more_specs.js']
            });

    b.bundle().pipe(source('specs.js')).pipe(gulp.dest('./dist'));
})

I want to replace entries with a dynamically created filtered list of files, so that instead of having to update the array every time I add a new file I want Browserified, it would do this automatically.

To do this, I started to use gulp-filter to select the files I wish to browserify from the folder:

gulp.src('lib/*.js')
    .pipe(gulpFilter('*_specs.js'))
    .pipe(concat('specs.js'))
);

But because this returns an asynchronous stream rather than an array, you can't use this in-place of entries. Then I thought that I could concatenate the separate files into the one virtual file, and then pass this into Browserify. Like this:

gulp.task('build-tests', function() {
    var b = browserify(
        gulp.src('lib/*.js')
            .pipe(gulpFilter('*_specs.js'))
            .pipe(concat('specs.js'))
        );

    b.bundle().pipe(source('specs.js')).pipe(gulp.dest('./dist'));
})

But this throws an unhandled error event - perhaps because the source files haven't been concatenated before the bundle method runs?

So that leads me to ask whether anyone has any experience performing something similar or along these lines? I'm quite new to gulp, so any pointers would also be appreciated. Thanks.


Solution

  • Use the glob module instead.

    var glob = require('glob').sync;
    
    gulp.task('build-tests', function () {
        var b = browserify({
            entries: glob(['./lib/**/*.js'])
        });
    
        b.bundle().pipe(source('specs.js')).pipe(gulp.dest('./dist'));
    });