Reed, picnic

Introduction to Gulp.js 12: Optimize CSS, JavaScript, Images and HTML

This is the 12th part of my series Introduction to Gulp.js. Today I will write tasks to optimize the assets of my website: CSS, JavaScript, Images and HTML.

Every Kilobyte, which has to be loaded will slow down the loading of my website. That’s why I will minimize all my CSS and JavaScript and run my images through an optimizer, to remove as many bytes as possible. I will also add a task for minimizing HTML, but I don’t use this task, because the reduction is minimal.


First I will write a task, which will optimize the CSS. Compass is able to minimize the CSS for production, but this Gulp.js task squeezed another 6 KB out of my files.

I install the needed Gulp.js plugins:

$ npm install --save-dev gulp-minify-css@1.2.1 gulp-size@2.0.0

This task will copy the CSS files from the assets folder, minimize them, remove comments, output the size of the file and copy them to the production assets folder.


Now the CSS is minimized and the same has to be done to the JavaScript files. I use UglifyJS for this task. If you don’t like it, go ahead and use a Google Closure or YUI compressor Gulp.js task.

$ npm install --save-dev gulp-uglify@1.0.1

This task will take the JavaScript files, minimize and optimize them, put them to my production assets folder and output the size.


Next I will take care of the images. They need to be copied to the production assets folder and crunshed (reduce the size). This may take a while, depending on the size and amount of your images, that’s why I only optimize the images for production.

Show more details

To get a more detailed output in Gulp.js you may add a flag to your command: gulp publish --verbose. It will list each individual image for the optimize task and how much it was compressed.

I’ll need gulp-imagemin for my task, which is able to minify PNG, JPG, GIF and SVG images:

$ npm install --save-dev gulp-imagemin@2.3.0

This task will take my images, optimize them, copy them to the assets folder and output the size.


As said before I wrote this task, so you can see how to do it, but I don’t use it, because the reduction is minimal and not worth the messy markup. I like to keep it readable so other people can learn from it.

$ npm install --save-dev gulp-htmlmin@1.2.0

Source Code

View Source on GitHub


This concludes the 12th part of my series Introduction to Gulp.js. Today we learned how to minimize CSS and JavaScript files and reduce the size of images.

This article was first published on
One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.