Mat*_*ius 4 javascript css c# .net-4.5 bundling-and-minification
我正在使用.NET 4.5 System.Web.Optimization捆绑.当打开最小化文件时,我发现有些CSS和JavaScript没有通过验证机制而被最小化.这些文件的消息写得像
/* Minification failed. Returning unminified contents.
(5616,18): run-time error CSS1036: Expected expression, found '@Arial'
Run Code Online (Sandbox Code Playgroud)
因为类有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
*/
Run Code Online (Sandbox Code Playgroud)
我确实理解正确的解决方案是修复错误,但是有很多文件有很多错误,这些可能是有时需要解决的麻烦.有没有办法在捆绑时禁用css/js的验证,或者必须使用自定义IBundleTransform编写器来删除像"use strict"捆绑和缩小的javascript文件之类的东西?
您可以通过编写自己继承的类来完成此任务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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后在BundleConfig.cs中,使用LicensedStyleBundle而不是StyleBundle:
bundles.Add(new LicensedStyleBundle("~/Content/css").Include("~/Content/site.css"));
Run Code Online (Sandbox Code Playgroud)
您可以为ScriptBundle执行类似的代码.如果你需要指针,所有源代码都在NuGet包的Github项目站点,并且只需要稍微调整就可以忽略错误,就像上面的代码一样.
| 归档时间: |
|
| 查看次数: |
1801 次 |
| 最近记录: |