Min: Honey I shrunk my CSS

Learning Gulp : part 6 of 22 published on Jul 22, 2015

Now since we have our css in a single file, we can continue to increase the performance of our site by minifying our css. Minifying is the process of eliminating all the unnecessary formatting in a css file. Human’s need spaces and tabs (also known as white space) to more easily read the styles. A browser doesn’t care about white space so we can make the file smaller by removing them.

You should start seeing a pattern when using gulp…. because for this we need to use a plugin. :P

$ npm install gulp-minify-css --save-dev
// gulpfile.js
var gulp = require('gulp');
var concat = require('gulp-concat');
var clean = require('gulp-rimraf');
var cssmin = require("gulp-minify-css");

gulp.task('clean', [], function() {
  console.log("Clean all files in build folder");

  return gulp.src("build/*", { read: false }).pipe(clean());
});

gulp.task('default', ['clean'], function() {
  console.log("Concat, move, and minify all the css files in styles folder");
  return gulp.src("contents/styles/**.css")
      .pipe(concat('main.min.css'))
      .pipe(cssmin())
      .pipe(gulp.dest('build/styles'));
});
$ gulp
Using gulpfile ~/YOUR_DIRECTORY/gulpFile.js
Starting 'clean'...
Clean all files in build folder
Finished 'clean' after 18 ms
Starting 'default'...
Concat, move, and minify all the css files in styles folder
Finished 'default' after 40 ms

Our build/styles/main.min.css should now look like:

p{font-size:30px}h1{color:red}

We have successfully moved our css files, concat’d them together, and now minified them into a tiny, optimized package.

Next: Streams