GithubHelp home page GithubHelp logo

deanhume / html-minifier Goto Github PK

View Code? Open in Web Editor NEW
133.0 17.0 86.0 26.06 MB

A simple command line tool to minify your HTML, Razor views & Web Forms views

License: MIT License

C# 100.00%
c-sharp html-minifier razor-views knockout webperformance pagespeed

html-minifier's Introduction

HTML Minifier

A simple command line tool to minify your HTML, Razor views & Web Forms views. By minifying your HTML on bigger web pages, you will save on bytes that your users need to donwload. Less bytes equal faster web pages & faster web pages equal happy users!

Getting Started

Go from HTML that looks like this:

<h2>
    Admin Menu</h2>
<ul>
    <li>@Html.ActionLink("Edit blog entries", "List", "Admin")</li>
    <li>@Html.ActionLink("View Comments", "CommentList", "Admin")</li>
    <li>@Html.ActionLink("Clear Cache", "ClearCache", "Admin")</li>
</ul>

To HTML that looks like this:

<h2> Admin Menu</h2><ul><li>@Html.ActionLink("Edit blog entries", "List", "Admin")</li><li>@Html.ActionLink("View Comments", "CommentList", "Admin")</li><li>@Html.ActionLink("Clear Cache", "ClearCache", "Admin")</li></ul>

Usage Examples

In order to use from the command line, you simply pass through a folder path that contains all of the files you want to minify. The minifier will process all images in the root and subfolders.

C:\>HtmlMinifier.exe "C:\Folder"

If you'd like to restrict the number of characters per line and force it to break to the next line, use the minifier with the following optional value (where the number is the max character count).

C:\>HtmlMinifier.exe "C:\Folder" "60000"

There is also the option to disable certain minification features. For example, if you use a you rely on HTML comments (Knockout, Angular, etc.) you might want to leave them in the minified HTML.

C:\>HtmlMinifier.exe "C:\Folder" ignorehtmlcomments

You can also disable the minification of JavaScript Comments

C:\>HtmlMinifier.exe "C:\Folder" ignorejscomments

If you use knockoutJS, you can optionally disable the minification of Knockout Comments

C:\>HtmlMinifier.exe "C:\Folder" ignoreknockoutcomments

If you want to minify individual folders you can do:

C:\>HtmlMinifier.exe "C:\Folder\fld1" "C:\Folder\fld2"

If you want to minify individual files you can do:

C:\>HtmlMinifier.exe "C:\Folder\file1.html" "C:\Folder\file2.html"

If you'd like to find out how to use this with MSBUILD and your next publish, please follow this link.

License

(C) Dean Hume 2022, released under the MIT license

html-minifier's People

Contributors

aderman avatar ashleymedway avatar bmorrelli avatar deanhume avatar heldersepu avatar ibrahimozgon avatar kblok avatar marekvse avatar miroradenovic avatar rposbo avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

html-minifier's Issues

Razor text mode does not minify properly

When including html that has this, the minification does not properly account for this (I believe razor needs the @: on a single line by itself, minifying the html causes an error).

I somehow can't get read access to this repository, but you'll need the following code in StreamReaderExtension.cs to fix this:

// Replace Razor "@:" (text mode) instances
htmlContents = Regex.Replace(htmlContents, @"@:\s", "{{{TEXT_MODE}}}");

Further below....
htmlContents = htmlContents.Replace("{{{TEXT_MODE}}}", "\r\n@:\r\n");

var test = "1";// COMMENT

There is a bug for comments.

CSHTML FILE
@{
decimal FirstPrice = 10;//priceList.PriceList.First(d => d.TotalSession == 1 && d.Duration == 60).Price;
}

1

RESULT
@{ decimal FirstPrice = 10;//priceList.PriceList.First(d => d.TotalSession == 1 && d.Duration == 60).Price; }

1

// means all codes are comments and not included.

Can you fix?

utf8

no support utf8 character
(arabic language)

Regex issue with javascript line comments

Line 161 in StreamReaderExtension.cs:
htmlContents = Regex.Replace(htmlContents, @"// (.*?)\r?\n", "", RegexOptions.Singleline);

This catches regex expressions in javascripts that have escaped forward slashes. For example:
url += $('#field').val().replace(///g, '').replace(/&/g, 'and').substring(0, 50) + '/';

the regex expression "///g" is valid, but not a comment.

Trying to think of a workaround for this line, but my regex is a little rusty.

I was thinking this:
htmlContents = Regex.Replace(htmlContents, @"[^\\]// (.*?)\r?\n", "", RegexOptions.Singleline);

But that also fails.

Razor @: error still broken after v1.7

I hate to be a thorn in anyone's side but v1.7 did not fix this issue, razor "@:" need to be on its own line or it breaks, it is still broken in 1.7, I don't know why it was closed as fixed when it is not.

test:

@if (true) {
@:


}

Content of <pre> tag should not be minified

Text in a <pre> element is displayed in a fixed-width font (usually Courier), and it preserves both spaces and line breaks.

This sample:

<div>
<pre>
TEST
Hello
World
</pre>
</div>

is not the same as:

<div><pre> TEST Hello World </pre></div>

Minification problem

Hey!
When trying to minify the following view:

@using ClassLibrary1
@model IList<GenericViewModel>

<article class="list-widget list-widget--col2">
  <h1 class="list-widget__title">Title</h1>
  @if (Model!= null && Model.Count > 0)
  {
   <ul class="list-widget__list">
     @foreach (var item in Model)
     {
       <li class="list-widget__list-item">
        <a href="@item.Url" class="list-widget__item-link">
          <em class="list-widget__list-item-info">@item.SubTitle</em>
          <span>@item.Title</span>
        </a>
      </li>        
     }
  </ul>  
  }  
</article>

The result was broken

@model IList<GenericViewModel><article 
@using ClassLibrary1 class="list-widget list-widget--col2"><h1 class="list-widget__title">Title</h1> @if (Model!= null && Model.Count > 0) { <ul class="list-widget__list"> @foreach (var item in Model) { <li class="list-widget__list-item"><a href="@item.Url" class="list-widget__item-link"><em class="list-widget__list-item-info">@item.SubTitle</em><span>@item.Title</span></a></li> } </ul> } </article>

The <article here is broken, i temporarily fixed it by switching:

@using ClassLibrary1
@model IList<GenericViewModel>

to

@model IList<GenericViewModel>
@using ClassLibrary1

Which i believe is the last > that causes problem.

Issue with non-standard characters

Hi,

First of all, HTML minifier is a very good stuff. But my page's language is hungarian, and the minifier brokes all of the hungarian specific characters like ÁÉŐÓÜ....

Could you solve this issue?

Dictionary as Razor model

When the model definition is a Dictionary or other key-value list, the definition for is being split halfway through, it looks to happen on the comma ',' character. Then the rest of the minified contents are on the same line as the second half of the definition, causing a parser error.

Line 1: @model Dictionary<string,
Line 2: MyAssemblyName.Setting[]> @{ ViewData["Title"] = "Settings"; ......

Edit: Found this happens when there is a space after the comma, when there's no space the program works fine. But VS adds a space after the comma when the page is formatted.

File extension problem

I have some javascript files which name include "aspx" string.

For example: codes.aspx.js

html-minifier try to minify them becasure their name include "aspx". Minifier crash from these files.

Razor @: error

If a Razor page uses @: it might break as the html-minifier makes no special exceptions for it they should be on their own lines or at least end the line. @: requires line break to end tag.

@"@:(.*?)\r?\n" regex should find them, before minimization.

JavaScript single-line comments begin with a double forward slash (//)

The inline JavaScript code with single-line comments begin with a double forward slash (//) causes to comment the remainder of javascript code on minimized html file; e.g.:

<script>
    var a; // this is a comment
    a = 3;
</script>

Minified:

<script>var a; // this is a comment a = 3;</script>

Html conditional comment - opening and closing in two tags

Code below brokes when minified. Html conditional comments in two comment tags (opening and closing) not working.

Example of not supported html :

<!--[if !IE]><!-->
<html lang="fr">
<!--<![endif]-->

More complex example:

<!DOCTYPE html>
<!--[if IE 8]> <html lang="fr" class="ie8"> <![endif]-->
<!--[if IE 9]> <html lang="fr" class="ie9"> <![endif]-->
<!--[if !IE]><!-->
<html lang="fr">
<!--<![endif]-->

....

Add better feedback in the console

It would be good to see more feedback come through on the console when you are running through the commands. Could consider:

  • Progress bar
  • How much was saved in total
  • Something fun like ASCII art 🎱

c# comment "//" on razor view cannot be ignored

for example, when there are c# comment "//" in .cshtml file, the output will become 1 line and all will be commented
@{
//ViewBag.Title = "Form Detail";
ViewBag.Title = @Resources.Global.FORM_DETAIL + "(" + @Resources.Global.SNAPSHOT +")";
}

->
@{ //ViewBag.Title = "Form Detail"; ViewBag.Title = @Resources.Global.FORM_DETAIL + "(" + @Resources.Global.SNAPSHOT +")"; }

Problem with special characters

It seems like it has a problem with a couple of German letters: ä, ü, ö, ß
Moreover it can't handle special characters and symbols like: -, ©, etc.

Kind regards
Joe

minify js file encode error

services.AddWebMarkupMin(
options =>
{
options.AllowMinificationInDevelopmentEnvironment = true;
options.AllowCompressionInDevelopmentEnvironment = true;
})
.AddHtmlMinification(
options =>
{
options.MinificationSettings.RemoveRedundantAttributes = true;
options.MinificationSettings.RemoveHttpProtocolFromAttributes = true;
options.MinificationSettings.RemoveHttpsProtocolFromAttributes = true;
options.MinificationSettings.RemoveTagsWithoutContent = true;
options.MinificationSettings.MinifyEmbeddedJsCode = true;
options.MinificationSettings.MinifyEmbeddedCssCode = true;
})
.AddHttpCompression();

app.UseWebMarkupMin();`

js file content with chinese char show error in browser

image
file encode with utf-8 without bom

Minification problem when using @inherits ...<>

Since I'm using Nancy with Razor, I have to add @inherits Nancy.ViewEngines.Razor.NancyRazorViewBase to the top of each view in order to enable intellisense (it appears to work without being on the top of each view, but I believe this is common to those who use Nancy with Razor to place it at the top)

Similar to issue #10 I believe it's due to the fact it ends with >

As a temporary workaround I've moved the @Inherits section to the very bottom of the view.

Root Directory Minification

Files in the root are not being minified. I saw a closed issue saying that this has been fixed in the latest version but I can't seem to get it to work.

IE Comments Removed

It seems deliberate as you have a test case for this, but why are the IE html comments removed?

<!--[if lt IE 7 ]><html class="ie ie6" lang="en"> <![endif]-->

I'm happy for comments like <!-- This is a line of HTML --> to be removed.

However removing the IE conditions isn't just minifiying the HTML its modifying it.

Multiple * Bug

The job is loading for a very long time or it doesn't complete.

I read #36, but it is not working.

My code
`




@if (true) {
    }
    else
    {

    }
</div>
`

Razor error comments "//" in @{}

test:

@{
/*Layout = "~/Views/Shared/_layout.cshtml";*/
// Layout = "~/Views/Shared/_layout.cshtml";
//Layout = "~/Views/Shared/_layout.cshtml";
}

to

@{ //Layout = "~/Views/Shared/_layout.cshtml"; }

Inline tag bug

The code <b>click</b> <a href=xxx>here</a> will be displayed as "clickhere" (no space)

Issue with accents in words

There is problem with accents in words.
I'm using Asp.net MVC, and when try to use html-minifier, some words on my website display are incorrect.
Example :
<h4><i class="fa fa-play-circle-o"></i>Xem gì hôm nay?</h4>
-->
<h4><i class="fa fa-play-circle-o"></i>Xem gì hôm nay?</h4>
Please help me how to fix it

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.