问题
I use mustache/handlebar templates.
eg:
<script id="contact-detail-template" type="text/html">
<div>... content to be compressed </div>
</script>
I am looking to compress/minify my HTML files in the templates for the best compression.
YUIcompressor, closure does not work as they think that it is script and gives me script errors.
HTMLCompressor does not touch them even as it thinks that it is a script.
How do I minify the content in the script tags with type text/html? Can I use a library? If not, is sed or egrep a preferable way? Do you have sed/egrep syntax to remove empty lines (with just spaces or tabs), remove all tabs, trim extra spaces?
Thanks.
回答1:
sed -e "s/^[ \t]*//g" -e "/^$/d" yourfile
This will remove all the extra spaces and tabs from the begining, and remove all empty lines.
sed -e "s/^[ \t]*//g" -e ":a;N;$!ba;s/\n//g" yourfile
This will remove all the extra spaces and tabs from the begining, and concatenate all your code.
Sorry if i missed something.
回答2:
Try using Pretty Diff to minify this kind of code. It will only assume the stuff inside script tags is JavaScript if there is no mime type or if the type is one of the various JavaScript types. It is also intelligent enough to know which white space is okay to remove without corrupting the output of content or the recursive beautification of code later.
回答3:
Use sed ':a;N;$!ba;s/>\s*</></g' file
, it enables to you remove whitespaces and newlines where unneeded. Unlike ghaschel example, this doesn't remove those useful whitespaces in the beginning of the line as it preserves <pre>
and <p>
tags.
This is useful as you can remove whitespaces between >
and <
which is a common method to enlarge a html file. This example could also be used for a XML file like atom feed and rss feed for example.
I personally use this as a pipe in my site generator, this can reduce a normaly file size and can be use in conjunction with gzip.
来源:https://stackoverflow.com/questions/12376368/minify-html-files-in-text-html-templates