11

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

quasoft
  • 5,291
  • 1
  • 33
  • 37
Steve Tomlin
  • 3,391
  • 3
  • 31
  • 63

4 Answers4

10

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/'));
});
Falk Jäger
  • 436
  • 6
  • 12
Eran Shabi
  • 14,201
  • 7
  • 30
  • 51
3

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.

joaomilho
  • 585
  • 4
  • 8
2
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();
});
Willy
  • 3,506
  • 3
  • 22
  • 35
1

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
    });
Aftab Ahmed
  • 665
  • 9
  • 17