Asp.Net Mvc ScriptBundle 脚本文件捆绑压缩 导致 脚本出错的问题

由于捆绑压缩会对所有包含的文件进行压缩,无法设置忽略对某个js文件的压缩。导致压缩该js后,脚本出错的问题。

解决方式:

  重写 ScriptBundle 的 GenerateBundleResponse 。代码如下

  

public class ScriptBundleFileIgnoreZip: ScriptBundle
{ readonly HashSet<string> bundles = new HashSet<string>(); /// <summary>
/// 构造函数
/// </summary>
/// <param name="virtualPath"></param>
public ScriptBundleFileIgnoreZip(string virtualPath) : base(virtualPath) { } /// <summary>
/// 忽略压缩包含文件
/// </summary>
/// <param name="virtualPaths">文件组</param>
/// <returns></returns>
public Bundle IgnoreMinInclude(params string[] virtualPaths)
{
foreach (string path in virtualPaths)
{
string cPath = path.TrimStart('~');
if (!bundles.Contains(cPath))
{
bundles.Add(cPath);
}
} return base.Include(virtualPaths);
} /// <summary>
/// 生成压缩捆绑响应文
/// </summary>
/// <param name="context">捆绑上下文</param>
/// <returns></returns>
public override BundleResponse GenerateBundleResponse(BundleContext context)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
IEnumerable<BundleFile> enumerable = this.EnumerateFiles(context);
enumerable = context.BundleCollection.IgnoreList.FilterIgnoredFiles(context, enumerable);
enumerable = this.Orderer.OrderFiles(context, enumerable);
if (this.EnableFileExtensionReplacements)
{
enumerable = context.BundleCollection.FileExtensionReplacementList.ReplaceFileExtensions(context, enumerable);
} StringBuilder bundleContent = new StringBuilder();
string text2 = ";" + Environment.NewLine;
Microsoft.Ajax.Utilities.Minifier minifier = new Microsoft.Ajax.Utilities.Minifier();
foreach (var bf in enumerable)
{
if (bundles.Contains(bf.VirtualFile.VirtualPath))
{
bundleContent.Append(bf.ApplyTransforms());
}
else
{
bundleContent.Append(minifier.MinifyJavaScript(bf.ApplyTransforms(), new Microsoft.Ajax.Utilities.CodeSettings()
{
EvalTreatment = Microsoft.Ajax.Utilities.EvalTreatment.MakeImmediateSafe,
PreserveImportantComments = false
}));
} bundleContent.Append(text2);
} if (this.Transforms != null)
{
this.Transforms.Clear();
} return this.ApplyTransforms(context, bundleContent.ToString(), enumerable); }

用法:

 var scriptBundles = new ScriptBundleFileIgnoreZip("~/JS");

 scriptBundles.Include("~/要压缩的文件0.js");
scriptBundles.IgnoreMinInclude("~/忽略压缩的文件.js")
.Include("~/要压缩的文件1.js", "~/要压缩的文件2.js"); BundleTable.Bundles.Add(scriptBundles);
上一篇:【DWR系列06】- DWR日志及js压缩


下一篇:YUI Compressor 压缩 JavaScript 原理-《转载》