cssgruntjssource-mapsgrunt-contrib-cssmingruntfile

cssmin grunt plugin generates incorrect source urls in sourcemap


cssmin grunt plugin grunt-contrib-cssmin trims leading slash in css sourcemap sources url, thus making css mapping incorrect. Meanwhile after editing sourcemap file by hand (adding leading slash to each source url) everything seems to be mapped correctly. Original sourcemap file is taken from annotation in original css (unminified), which is generated correctly by other grunt plugins.

My file structure:

web (resource root)
├─css
│ └─..(css files)
└─less
  └─..(less files)

Sourcemap of original (unminified) css – sources urls are correct. Generated by grunt-contrib-less and grunt-autoprefixer respectively:

{"version":3,"sources":["/less/base/normalize.less","/less/base/boilerplate.less"...

Sourcemap of minified css – leading slashes for source files disappeared. Generated by grunt-contrib-cssmin:

{"version":3,"sources":["less/base/normalize.less","less/base/boilerplate.less"...

Part of my gruntfile.js:

module.exports = function(grunt) {

  grunt.initConfig({
    cssmin: {
      options: {
        shorthandCompacting: false,
        sourceMap: true,
        roundingPrecision: -1
      },
      target: {
        files: {
          'web/css/style.min.css': 'web/css/style.css'
        }
      }
    }
  });
};

Solution

  • By now I solved this problem with grunt-string-replace plugin. I configured my gruntfile.js so that it adds leading slashes to source files in sourcemap:

    module.exports = function(grunt) {
    
      grunt.initConfig({
        'string-replace': {
          dist: {
            files: {
              'web/css/style.min.css.map': 'web/css/style.min.css.map'
            },
            options: {
              replacements: [{
                pattern: /"([^"])*(less\/)/g,
                replacement: '"/less/'
              }]
            }
          }
        }
    
        // other code
    
      });
    };
    

    Well, it's a hack, because it requires additional grunt plugin. But it solved the problem.