首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在使用System.Web.Optimization捆绑最小化时,是否有一种禁用js/css验证的方法?

在使用System.Web.Optimization捆绑最小化时,是否有一种禁用js/css验证的方法?
EN

Stack Overflow用户
提问于 2014-08-20 11:54:17
回答 1查看 2.2K关注 0票数 6

我正在使用.NET 4.5 System.Web.Optimization捆绑。当捆绑文件的最小化打开时,我发现一些CSS和JavaScript没有通过验证机制而被最小化。这些文件的消息编写如下

代码语言:javascript
复制
/* Minification failed. Returning unminified contents.
(5616,18): run-time error CSS1036: Expected expression, found '@Arial'

因为班里有font-family: @Arial Unicode MS;

或者在全局变量前面没有window的Javascript在错误之后产生。

代码语言: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"之类的内容?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-08-20 16:15:35

您可以通过编写从IBundleBuilder继承的自己的类来实现这一点。

下面的代码是一个相关的NuGet包LicensedBundler的改编,它保留重要的注释并缩小文件,同时不减少错误文件,而是将它们及其错误移到包的顶部( ASP.NET捆绑的默认功能是不缩小任何内容)。如您所见,在CssSettings中有一个忽略所有错误的选项:

代码语言:javascript
复制
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

代码语言:javascript
复制
bundles.Add(new LicensedStyleBundle("~/Content/css").Include("~/Content/site.css"));

您可以为ScriptBundle执行类似的代码。如果您需要指针,那么所有的源代码都位于Github项目站点的NuGet包中,只需要做一些小的调整就可以忽略错误,就像上面的代码所做的那样。

票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/25404041

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档