OneBite.Dev - Coding blog in a bite size

Minify CSS files with Gulp JS

Learn how to Minify CSS files with Gulp JS to make it load faster

Learn how to Minify CSS files with Gulp JS to make it load faster.
We will use gulp-clean-css

Using Gulp Clean CSS

install

npm install gulp-clean-css --save-dev

basic usage

const gulp = require('gulp');
const cleanCSS = require('gulp-clean-css');
 
gulp.task('minify-css', () => {
  return gulp.src('styles/*.css')
    .pipe(cleanCSS({compatibility: 'ie8'}))
    .pipe(gulp.dest('dist'));
});

Combine it with previous example

We’ve seen how to combine multiple CSS files into a single file
Let’s combine it with this minify process

const gulp = require('gulp');
const concat = require('gulp-concat');
const cleanCSS = require('gulp-clean-css');

function cssTask() {
    return gulp.src('dev/css/*.css')
             .pipe(concat('style.css'))
             .pipe(cleanCSS({compatibility: 'ie8'}))
             .pipe(gulp.dest('dist/css'))
}
exports.default = cssTask

Show source map (original CSS file)

For easier debugging, we sometimes play with inspect element in browser, but after minifying our CSS file, it’s hard to see them again.
That’s why we will allow sourcemap

Install gulp sourcemap

npm i gulp-sourcemaps --save-dev

Use it

const gulp = require('gulp');
const concat = require('gulp-concat');
const cleanCSS = require('gulp-clean-css');
const sourcemaps = require('gulp-sourcemaps'); //newly added

function cssTask() {
    return gulp.src('dev/css/*.css')
             .pipe(sourcemaps.init()) //newly added
             .pipe(concat('style.css'))
             .pipe(cleanCSS({compatibility: 'ie8'}))
             .pipe(sourcemaps.write('.')) //newly added
             .pipe(gulp.dest('dist/css'))
}
exports.default = cssTask
← Combine multiple CSS file...
Compress image with GulpJ... →
gulpjs