Search code examples
csssassgruntjsminifybuild-system

Is there a way to remove important comments?


I minified my css file, but it did not get rid of /*! important comments */.

is there a way to get rid of important comments?

I found this - grunt-contrib-cssmin - how to remove comments from minified css but @Rigotti answer does not work for important comments.

Thanks for your help!


Solution

  • Many grunt plugins will not remove the important comments as the notation /*! */ is typically used to prevent removal. However, grunt-strip-css-comment, provides the option to remove them.

    You could apply the following stripCssComments Task to your minified .css file.

    Gruntfile.js

    module.exports = function(grunt) {
    
      require('load-grunt-tasks')(grunt);
    
      grunt.initConfig({
        cssmin: {
          // ...
        },
        stripCssComments: {
            options: {
              preserve: false // <-- Option removes important comments.
            },
            dist: {
                files: {
                    // Redefine paths as necessary.
                    // These should probably both be the same given your scenario.
                    'path/to/dest/file.min.css': 'path/to/src/file.min.css'
                }
            }
        }
      });
    
      // Define the alias to the `stripCssComments` Task after your `cssmin` Task. 
      grunt.registerTask('default', ['cssmin', 'stripCssComments']);
    };
    

    Install:

    cd to your project directory and run:

    npm i -D grunt-strip-css-comments load-grunt-tasks
    

    Note: grunt-strip-css-comments is loaded using the plugin load-grunt-tasks instead of the typical grunt.loadNpmTasks(...) notation, so you'll need to install that too.