Skip to content Skip to sidebar Skip to footer

How To Set Up Gulp To Bundle Several Files Into One?

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 director

Solution 1:

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/'));
});

Solution 2:

The right answer is: there is no legit need for concatenating JS files using gulp. Therefore you should never do that.

Instead, look into proper JS bundlers that will properly concatenate your files organizing them according to some established format, like commonsjs, amd, umd, etc.

Here's a list of more appropriate tools:

Note that my answer is around end of 2020, so if you're reading this in a somewhat distant future keep in mind the javascript community travels fast so that new and better tools may be around.

Solution 3:

var gulp = require('gulp');
var concat = require('gulp-concat');
gulp.task('js', function (done) {
    // array of all the js paths you want to bundle.var scriptSources = ['./node_modules/idb/lib/idb.js', 'js/**/*.js'];
    gulp.src(scriptSources)
        // name of the new file all your js files are to be bundled to.
        .pipe(concat('all.js'))
        // the destination where the new bundled file is going to be saved to.
        .pipe(gulp.dest('dist/js'));
    done();
});

Solution 4:

Use this code to bundle several files into one.

gulp.task('scripts', function() {
      return gulp.src(['./lib/file3.js', './lib/file1.js', './lib/file2.js']) //files separated by comma
        .pipe(concat('script.js'))   //resultant file name
        .pipe(gulp.dest('./dist/')); //Destination where file to be exported
    });

Post a Comment for "How To Set Up Gulp To Bundle Several Files Into One?"