Optimizing files with Gulp

Epilogue Of Gulp Series

gulp-1

Optimizing JavaScript and CSS

Optimizing JavaScript and CSS is done at two stages one is concatenation another one is minification. To concatenate files we will use the gulp-useref plugin and for the minification, we will use gulp-uglify for JavaScript and gulp-cssnano for CSS and additionally to check the file type we will use the gulp-if plugin. To concatenate files gulp offers yet another plugin called gulp-concatenate, but it is hard to concatenate files with this plugin if the files are located in different files.

This process takes all the targeted files and combine all the codes and generate a single file, it will avoid multiple requests to the server thus speed of the page load will significantly increase.

Read more about how concatenation improves page load?

Install the previously mentioned gulp plugins gulp-useref, gulp-uglify, and gulp-if by using the following command.

npm install gulp-uglify gulp-cssnano gulp-if gulp-useref --save-dev

Before we create and run the gulp-concatenate task, we should mention which scripts, stylesheet to be concatenated on html files. In our example we have the index.html page on app folder, as well we have two JavaScript files on js sub-folder and two stylesheet on css sub-folder of app folder, first include them in the index.html page using script tag and mark them as follows.

build

The comment starts with the build: and ends with endbuild, the suffix js after the word build tells the useref that the file type it’s going to concatenate is JavaScript and js/main.min.js is the name of the output file. The JavaScript files that exist between build tag is taken to concatenate by the useref while running the task, same applies for CSS. Next, we will create the useref task on gulpfile.js.

gulp.task('useref', function(){
  return gulp.src('app/*.html')
    .pipe(useref())
    .pipe(gulpIf('*.js', uglify()))
    .pipe(gulpIf('*.css', cssnano()))
    .pipe(gulp.dest('dist'))
});

The gulp useref task takes all the html files and executes files that exists under the build comment, it concatenates and move ahead in the pipe and JavaScript output is minified using uglify() and CSS output is minified using cssnano() finally the minified files are saved under the dist folder.

Moving Fonts from app to dist folder

There is no need to optimize the font files since we can simply move them from app folder to dist folder using the following task.

gulp.task('fonts', function(){
    return gulp.src('app/fonts/**/*')
        .pipe(gulp.dest('dist/fonts'))
});

This task will move all the font files exist under fonts folder to the dist/fonts folder.

Optimizing Images

To optimize images we will use gulp-imagemin plugin, we will install and create gulp task to optimize images, however compressing is time consuming task than other process since we will use gulp-cache to reduce, gulp-cache will ensure only the new or changed images get compressed. We will wrap the imagemin function using cache funtion

npm install gulp-imagemin gulp-cache --save-dev

gulp.task('images', function(){
    return gulp.src('app/images/**/*.+(png|jpg|jpeg|gif|svg)')
        .pipe(cache(imagemin()))
        .pipe(gulp.dest('dist/images'))
});

Note: We can set interlace, optimization level with imagemin() function, head to plugin description for more details.

Cleaning up dist folder

Whenever we run useref task it generates a minified version of CSS and JavaScript with the latest modification(s), since before we save them into the dist folder we should clean up the folder, we will use del plugin from npm to clean up the dist folder.

npm install del --save-dev

gulp.task('clean:dist', function() {
    return del.sync('dist');
})

Note: Deleting images folder under dist won’t require for the fresh run of imagemin() function since we have cached the images using the cache().

So far we have created,

  • sass() to compile SASS to CSS
  • useref() to concatenate and minify JavaScript and CSS
  • images() to optimize images
  • fonts() to copy fonts to dis
  • clean:dist() to clean up dist folder

We have already grouped the browserSync and sass task together, now we will group all above mentioned task under the name build, we should execute these tasks sequentially as mentioned above, run-sequence package from npm allows us to run gulp tasks one after one. We will install run-sequence package from npm and we will create build task with run-sequence.

npm install run-sequence --save-dev

gulp.task('build', function (callback) {
  runSequence('clean:dist', 
    ['sass', 'useref', 'images', 'fonts'],
    callback
  )
})

The build task first runs clean:dist to delete files exists under dist folder then runs rest of the task sequentially.

Remember, we have previously grouped the browserSync and sass task under watch task for consistency we would change the watch task as we have created build task.

gulp.task('default', function (callback) {
  runSequence(['sass','browserSync', 'watch'],
    callback
  )
})

Note, we have replaced the old name watch with new name default, further, we can run this grouped task by typing gulp simply instead mentioning the task name.

In this introductory tutorial, we have covered few most useful Gulp plugins but there is a lot to explore. Gulp offers more than 3000 plugins, go head over to the official site of Gulp and explore more useful plugins which can help your pace of development.

Happy coding 🙂