我正在使用.NET 4.5 System.Web.Optimization捆绑。当捆绑文件的最小化打开时,我发现一些CSS和JavaScript没有通过验证机制而被最小化。这些文件的消息编写如下
/* Minification failed. Returning unminified contents.
(5616,18): run-time error CSS1036: Expected expression, found '@Arial'因为班里有font-family: @Arial Unicode MS;
或者在全局变量前面没有window的Javascript在错误之后产生。
/* Minification failed. Returning unminified contents.
(210,13-20): run-time error JS1300: Strict-mode does not allow assignment to undefined variables: PageObj
(189,13-20): run-time error JS1300: Strict-mode does not allow assignment to undefined variables: PageObj
*/我确实理解,正确的解决方案是修复错误,但是,有许多文件中有很多这样的错误,有时可能会很麻烦。是否有一种方法可以在捆绑时禁用css/js的验证,或者必须使用自定义的IBundleTransform编写器从打包和缩小的javascript文件中删除"use strict"之类的内容?
发布于 2014-08-20 16:15:35
您可以通过编写从IBundleBuilder继承的自己的类来实现这一点。
下面的代码是一个相关的NuGet包LicensedBundler的改编,它保留重要的注释并缩小文件,同时不减少错误文件,而是将它们及其错误移到包的顶部( ASP.NET捆绑的默认功能是不缩小任何内容)。如您所见,在CssSettings中有一个忽略所有错误的选项:
public class LicensedStyleBundle : Bundle
{
public LicensedStyleBundle(string virtualPath)
: base(virtualPath)
{
this.Builder = new LicencedStyleBuilder();
}
public LicensedStyleBundle(string virtualPath, string cdnPath)
: base(virtualPath, cdnPath)
{
this.Builder = new LicencedStyleBuilder();
}
}
public class LicencedStyleBuilder : IBundleBuilder
{
public virtual string BuildBundleContent(Bundle bundle, BundleContext context, IEnumerable<BundleFile> files)
{
var content = new StringBuilder();
foreach (var file in files)
{
FileInfo f = new FileInfo(HttpContext.Current.Server.MapPath(file.VirtualFile.VirtualPath));
CssSettings settings = new CssSettings();
settings.IgnoreAllErrors = true; //this is what you want
settings.CommentMode = Microsoft.Ajax.Utilities.CssComment.Important;
var minifier = new Microsoft.Ajax.Utilities.Minifier();
string readFile = Read(f);
string res = minifier.MinifyStyleSheet(readFile, settings);
content.Append(res);
}
return content.ToString();
}
public static string Read(FileInfo file)
{
using (var r = file.OpenText())
{
return r.ReadToEnd();
}
}
}然后在您的BundleConfig.cs中,使用LicensedStyleBundle而不是StyleBundle
bundles.Add(new LicensedStyleBundle("~/Content/css").Include("~/Content/site.css"));您可以为ScriptBundle执行类似的代码。如果您需要指针,那么所有的源代码都位于Github项目站点的NuGet包中,只需要做一些小的调整就可以忽略错误,就像上面的代码所做的那样。
https://stackoverflow.com/questions/25404041
复制相似问题