Resolve CSS Imports with gulp-cssimport

Posted on Jun, 21 2014, 0 comments

In my current build setup, I use SASS for writing my CSS and gulp as my task runner. Compiling my SASS code with gulp-sass works pretty well, but one thing kept bugging me for quite some time. 

There are a few cases where I have to rely on third-party CSS files. I use bower for dependency management and most libraries I require provide their own CSS file that I need to include somewhere in my website/application. Linking the file directly from the HTML is not an option, since this would create an additional HTTP request for each file, besides, I'd like to have all style-related stuff in one place. 

Another example is the use of Google Fonts. I don't want to rely on JavaScript for serving custom fonts and linking the file inside my HTML is not an option.

So in both cases I end up using an import-statement like the following:

@import 'http://fonts.googleapis.com/css?family=Annie+Use+Your+Telescope|Open+Sans:400,600,700';
@import '../components/library/lib.css';  

Unfortunately, this will be compiled to a classic CSS-Import statement which will also create an additional HTTP request.

I just recently discovered a gulp-plugin that helped me to get around this. It is called gulp-cssimport and basically parses a CSS file, finds imports, grabs the content of the linked file and replaces the import statement with it. Yay - exactly what I wanted :-).

I just added css-import to my build task and got rid of every additional request:

var gulp = require('gulp'),
    sass = require('gulp-ruby-sass'),
    autoprefixer = require('gulp-autoprefixer'),
    browserSync = require('browser-sync'),
    cssImport = require('gulp-cssimport');

  gulp.task('css', function() {
    return gulp.src('./scss/**/*.scss')
    .pipe(sass({
        style: 'compact',
        sourcemap: true
    }))
    .pipe(cssImport())
    .pipe(autoprefixer('last 1 version', '> 1%', 'ie 8', 'ie 7'))
    .pipe(gulp.dest('css'))
    .pipe(browserSync.reload({stream:true}));
});

It even works with remote resources like Google Fonts, so Page Speed Insights now has one reason less to yell at me :-).

▸ Post comment