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?
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);
});