简体   繁体   中英

How can I remove comments on-fly from my static CSS files?

I'm using facelets, and I have a number of CSS files in webapp/styles/blueprint/*.css . They contain comments which I don't want to become visible to end-users. How can I remove them on-fly?

Use YUI compressor . It will not only remove comments, but also minify the CSS (and JS) files.

Reader reader = null;
Writer writer = null;

try {
    reader = new InputStreamReader(new FileInputStream(cssFile), "UTF-8");
    writer = new OutputStreamWriter(new FileOutputStream(minFile), "UTF-8");
    new CssCompressor(reader).compress(writer, -1); // That's it.
} finally {
    close(writer);
    close(reader);
}

See also

As Nick Craver said in the comments, you should, if at all, do that work as a part of your building process since css is a static resource. No runtime modifications needed.

Now depending on your build process, you could write a small script that simply strips out any comments, my first approach would be regular expressions:

cssFileContents = cssFileContents.replaceAll("/\*.*?\*/", ""); //with lazy quantifier on the "."!

In this case you need to make sure that the regex "."-metacharacter includes linebreaks.

Since css only allows block comments (/* ... */) and no line comments (// ... \\n), this is the only thing you need to replace.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM