Tuesday, May 13, 2014

ASP.NET 4.5 Bundling and Minification

Today I was playing around with the B&M feature ASP.NET provides. Since most of the open source libraries mandate to preserve the copy right text, one of my requirements is to preserve the copyright text. When I examined most of the libraries, the comments are placed under important comments /*!-------*/

So, my first approach was to create a custom bundle class, that use the default bundle builder class and a custom bundle transformation class. The custom bundle transform class will use the AJAX Minifier class (Microsoft.Ajax.Utilities.Minifier) to minify file with PreserveImportantComments = true

Everything had worked as expected and then I found that the entire global variables from all JavaScript files included in the bundle are listed at the top of the generated file. So, I decided to go with another approach.

  • Created a custom bundle class that uses a custom bundle builder class.
  • The custom bundle builder class use AJAX Minifier class to minify the files.
  • You can set code setting properties to control the minification process
public class CustomBuilder : IBundleBuilder
{
public string BuildBundleContent(Bundle bundle, BundleContext context, IEnumerable<System.IO.FileInfo> files)
{
var settings = new CodeSettings()
{
// LocalRenaming = Microsoft.Ajax.Utilities.LocalRenaming.KeepAll,
PreserveImportantComments = true,
RemoveUnneededCode = true,
EvalTreatment = EvalTreatment.MakeAllSafe
};

var content = new StringBuilder();
foreach (var fileInfo in files)
{
var minifier = new Microsoft.Ajax.Utilities.Minifier();
content.Append(minifier.MinifyJavaScript(ReadFile(fileInfo), settings));
content.Append(";");
content.Append(Environment.NewLine);
}

return content.ToString();
}

private string ReadFile(FileInfo file)
{
using (var r = file.OpenText())
{
return r.ReadToEnd();
}
}
}


public class CustomScriptBundle : Bundle
{
// Methods
public CustomScriptBundle(string virtualPath)
: this(virtualPath, null)
{
}

public CustomScriptBundle(string virtualPath, string cdnPath)
: base(virtualPath, cdnPath)
{
this.Builder = new CustomScriptBuilder();
}

}



Featured post

How to connect to Mongo Atlas from Robo 3T

If you use a local instance of MongoDB, you might be a great fan of Robo3T. However, if you are using Mongo Atlas, the Atlas web interface p...

Popular Posts