ligershark / WebOptimizer

A bundler and minifier for ASP.NET Core
Apache License 2.0
753 stars 113 forks source link

Minify HTML / Razor Pages #262

Open Beblia opened 1 year ago

Beblia commented 1 year ago

Can you please add the ability to minify html/razor pages? Currently I see that only css and js can be minified. Would be an awesome addition. This is for Blazor Web Server on .net 7. Thanks.

A9G-Data-Droid commented 7 months ago

Due to the extension framework, maybe an extension could be built from:

https://github.com/Taritsyn/WebMarkupMin

I have installed both WebOptimizer and WebMarkupMin to see if they play nice together. It's working for my project. I did a quick view-source before and after. I can see that my HTML become a single packed line after installing WebMarkupMin, so we can get the effect we want this way.

b9chris commented 2 months ago

HTML Minification is already built in to NUglify, which WebOptimizer uses to minify other assets like Javascript and CSS. You can use it in Razor Views easily enough.

Make a new Layout and use this:

@{
    var sb = new System.Text.StringBuilder();
    using(var sw = new System.IO.StringWriter(sb))
    {
        RenderBody().WriteTo(sw, HtmlEncoder);
    }

    var nuglifyResult = NUglify.Uglify.Html(sb.ToString());

    string html = null;
    //if (nuglifyResult.HasErrors)
    //{
        //html = String.Join("<br/>", nuglifyResult.Errors);
    //}
    //else
    //{
        html = nuglifyResult.Code;
    //}
}
@Html.Raw(html)

Then, just make your root Layout now have a Layout, like:

@{
  Layout = "_Root";
}

Where "_Root" is the name of the root layout that's performing the minification.

That's it, your HTML will be minified. You should be ready for some kind of weird behavior by the minifier. You can uncomment the commented parts if you want to see errors it throws. It can get a little fussy about perfectly normal HTML.