Minifying output HTML

Skip to first unread message

Michał Zając

Nov 9, 2018, 8:07:22 AM11/9/18
to hakyll

I was wondering if anyone could give me any tips on how to produce minified HTML files when building? 
Should I minify my templates or can I somehow write a Compiler that would do this?

Best regards,

Oct 31, 2019, 12:02:42 PM10/31/19
to hakyll
Hi Michał,

I use HTML Tidy to transform my HTML (in my case I both minify it for inclusion in RSS feeds and pretty-print it for the final HTML source). Here's the relevant code:

minifyHTML :: Item String -> Compiler (Item String)
minifyHTML = withItemBody $ unixFilter "tidy" (tidyOptionsHTML ++ tidyOptionsMinify)

tidyOptionsDefault =
    [ "-quiet"
    , "--output-encoding utf8"
    , "--tidy-mark no"
    , "--mute-id yes"
    , "--wrap 0"
    , "--keep-tabs yes"

tidyOptionsHTML =
    tidyOptionsDefault ++
    [ "--output-html yes"
    , "--logical-emphasis yes"
    , "--warn-proprietary-attributes no"
    , "--priority-attributes id,class,name,property,rel,href"
    , "--sort-attributes alpha"
    , "--merge-divs no"
    , "--merge-spans no"
    , "--drop-empty-elements no"

tidyOptionsMinify =
    [ "--vertical-space auto"

It can then be used as normal with `>>= minifyHTML`. Check out some of the other command line options available, mine might not be ideal for your use case.

Be warned that HTML Tidy will throw errors if it encounters malformed HTML, so if you're transforming the HTML in other ways you can run into errors that take time to debug. This can be turned off, but I find it useful to ensure that I'm outputting valid HTML.

Reply all
Reply to author
0 new messages