cssmin not correctly handling @import

user3204380 picture user3204380 · Jan 16, 2014 · Viewed 8.3k times · Source

I am using cssmin on files containing @imports. cssmin is recursively importing local files correctly, but for imports that point to a URL the imports are left inline. This makes the resulting minified CSS invalid because @ rules must be at the beginning of the file. Does anyone know a good solution or workaround to this problem?

Answer

Alex Carod picture Alex Carod · Feb 11, 2015

I have exactly the same problem with cssmin and @import, and i found a solution with grunt concat:

  1. Create a concat grunt task that:
  2. Put @import url in the begining of mified css file and replaces references of @imports url for "".
  3. Execute task concat:cssImport after cssmin task.

Grunt task Code: to execute (concat:cssImport)

 grunt.initConfig({     
   concat: {
      cssImport: {
            options: {

               process: function(src, filepath) {
                return "@import url(http://fonts.googleapis.com/css?family=Roboto:400,300,900);"+src.replace('@import url(http://fonts.googleapis.com/css?family=Roboto:400,300,900);', '');
              }
           }
         },
            files: {
                'your_location_file_origin/file.full.min.css': ['your_location_file_destination/file.full.min.css']
            }
        } )}

My inspiration comes from https://github.com/gruntjs/grunt-contrib-concat#custom-process-function.