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 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();
}
}