Home / How to preserve comments with the YUI Compressor

How to preserve comments with the YUI Compressor

I use the YUI Compressor to minify Javascript and CSS files. By default it will remove all comments from the files but there is a simple solution to retaining comments in files, which is often necessary for example when preserving copyright and license terms of use etc.

Default example

Take the following Javascript file example:

/* some copyright information here */

function foo(var1, var2, var3) {
        /* comment blah blah blah */
        if(var1 == var2) {
                // do something
        }
}

When minified using the default YUI Compressor settings, the resulting output will look like this:

function foo(c,b,a){if(c==b){}};

Note that all comments have been removed and the variable names have been replaced with shorter names.

How to preserve comments with the YUI Compressor

To preserve comments, simply add a ! after the opening /* and that comment block will remain in the compressed output. The ! will be stripped because it is unecessary and was not present in the original code.

Changing the above example to retain the first comment:

/*! some copyright information here */

function foo(var1, var2, var3) {
        /* comment blah blah blah */
        if(var1 == var2) {
                // do something
        }
}

When run through the YUI Compressor it will now look like this:

/* some copyright information here */
function foo(c,b,a){if(c==b){}};

Other tips and tricks

I’ll post some other tips and tricks when using the YUI Compressor in the coming weeks to change other formatting etc.