2

I am trying to do automation to concat and uglify js in gulp.

Here is my gulpfile.js:

gulp.task('compressjs', function() {
    gulp.src(['public/app/**/*.js','!public/app/**/*.min.js'])
    .pipe(sourcemaps.init())
    .pipe(wrap('(function(){"use strict"; <%= contents %>\n})();'))
    .pipe(uglify())
    .pipe(concat('all.js'))
    .pipe(rename({
        extname: '.min.js'
    }))
    .pipe(sourcemaps.write('.'))
    .pipe(gulp.dest('public/app'));
})

Do you think it is needed to wrap every file with (function(){"use strict"; <%= contents %>\n})(); to avoid conflict when every file is being join together? Do you think my gulp task is good, or it can even better for performing it's task?

user1995781
  • 19,085
  • 45
  • 135
  • 236

1 Answers1

8

Wrapping every file in a closure really isn't necessary for most code. There are some bad libs out there that leak vars, but I'd suggest you deal with them on a case by case basis and, if possible, issue Pull Requests to fix the problem or just stop using them. Usually, they can't be fixed as simply as wrapping them in a function.

The task you have above won't properly pass all files to the uglify task - you will need to concatenate first. You also don't need to rename as you can specify the full name in concatenate. Below is a well tested Gulp setup for doing exactly what you've asked:

gulp.task('javascript:vendor', function(callback) {
  return gulp.src([
      './node_modules/jquery/dist/jquery.js',
      './node_modules/underscore/underscore.js',
      './node_modules/backbone/backbone.js'
    ])
    .pipe(sourcemaps.init())
    // getBundleName creates a cache busting name
    .pipe(concat(getBundleName('vendor')))
    .pipe(uglify())
    .pipe(sourcemaps.write('./'))
    .pipe(gulp.dest('./public/app'))
    .on('error', handleErrors);
});
Baer
  • 3,690
  • 25
  • 24
  • what is your getBundleName function? – nightire May 19 '15 at 17:31
  • 1
    I do a SHA sum of require('package.json').name + require('package.json').version – Baer May 20 '15 at 18:35
  • What do you do, if you have already uglified (vendor) scripts? Does Gulp ignore them? – aProgger Jan 27 '21 at 09:56
  • Neither Gulp nor the sourcemaps or uglify plugins are not aware of whether or not a source file has been compressed or not. All files will be processed in the same way. Most vendor code is distributed in both a compressed and uncompressed form, and I'd highly recommend that you use the uncompressed form. Doing so gives the compression algorithm more to work with and gives you full sourcemaps. – Baer Jan 28 '21 at 17:49