1

我正在使用 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
 */

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

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

4

1 回答 1

6

找到了解决方案。我创建了一个派生自 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。

于 2015-06-27T23:27:46.107 回答