【问题标题】:Asp.Net Bundle - How to raise exception when minification failsAsp.Net Bundle - 缩小失败时如何引发异常
【发布时间】:2015-08-18 10:15:53
【问题描述】:

我正在使用 Asp.Net MVC 5 和 System.Web.Optimization 1.1.0.0 中的捆绑和缩小系统:

        bundles.Add(new ScriptBundle("~/angularLibraries").Include(
            ......
            ));

然后渲染Bundle:

@Scripts.Render("~/angularLibraries")

有时我会通过在浏览器中打开相应的 url 来手动检查我的包的状态,有时我会发现它们有错误。示例:

/* Minification failed. Returning unminified contents.
(262,145-152): run-time error JS1019: Can't have 'break' outside of loop: break a
(40,297-304): run-time error JS1019: Can't have 'break' outside of loop: break a
 */

因为当缩小失败时捆绑机制会返回未缩小的内容,所以直到我在浏览器中手动打开该捆绑包时我才知道错误。

如何设置捆绑系统以在缩小失败时引发异常,以便我可以立即意识到错误?

【问题讨论】:

    标签: asp.net asp.net-mvc asp.net-bundling


    【解决方案1】:

    找到了解决办法。我创建了一个从 ScriptBundle 派生并覆盖方法 ApplyTransforms 的自定义类:

    public class CustomScriptBundle : ScriptBundle
    {
        public CustomScriptBundle(string virtualPath)
            : base(virtualPath)
        {
        }
    
        public CustomScriptBundle(string virtualPath, string cdnPath)
            : base(virtualPath, cdnPath)
        {
        }
    
        public override BundleResponse ApplyTransforms(BundleContext context, string bundleContent, IEnumerable<BundleFile> bundleFiles)
        {
            BundleResponse bundleResponse = base.ApplyTransforms(context, bundleContent, bundleFiles);
    
            if (bundleResponse.Content.StartsWith("/* Minification failed. Returning unminified contents."))
                ExceptionManager.LogMessage("Minification failed for following bundle: " + context.BundleVirtualPath);
    
            return bundleResponse;
        }
    }
    

    我最终记录了一条消息(收到来自 Elmah 的电子邮件通知)并且没有引发异常,因为我默认情况下仅在生产环境中启用了缩小,并且该应用程序将继续正常运行。

    如果你抛出异常,你会看到这样的:

    此方案也适用于 StyleBundle。

    【讨论】:

    • 您是否解决了导致 JS1019 错误的问题?我有同样的问题,但找不到任何违反此规则的代码。
    • @kildareflare 在未缩小的输出中搜索该行(您可以将输出保存到文件中并在 notepad++ 中打开)。错误消息告诉您行号:“(262,145-152):运行时错误JS1019 ....”。在这种情况下为第 262 行。我就是这样解决的。
    • 嘿,是的,这就是我正在做的事情——虽然看不出它在抱怨什么。不过,我会继续挖掘,谢谢。
    猜你喜欢
    • 2012-09-27
    • 2011-01-14
    • 2020-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多