如何使用MVC.NET Bundle配置文件从js文件中删除console.log

时间:2017-10-03 11:51:51

标签: javascript asp.net-mvc minify

我当前的bundle config连接所有脚本文件并缩小它并生成一个文件。但是没有从js文件中删除 console.log 行,如何添加配置以删除 console.log()行是

       bundles.Add(
            new Bundle(
                "~/Scripts/js-bundle",
                new IBundleTransform[] {new JsMinify() }).Include(
            "~/Scripts/script1.js",
            "~/Scripts/script2.js",
            "~/Scripts/script3.js"))

我尝试添加LogRemoverTransform()但是我收到了一些错误

enter image description here

1 个答案:

答案 0 :(得分:1)

您需要通过实施Bundle Transformation来创建自己的IBundleTransform。您可以使用this regexborrowed from this question)获取console.logconsole.info等实例,并将其替换为空字符串。

public class LogRemoverTransform : IBundleTransform
{
    public void Process(BundleContext context, BundleResponse response)
    {
        var compiled = string.Empty;
        var pattern = "console.(log|debug|info|warn|error|assert|dir|dirxml|trace|group|groupEnd|time|timeEnd|profile|profileEnd|count)\\((.*)\\);?";

        foreach (var file in response.Files)
        {
           // read text from js file, and replace the the matched parts with empty string
            compiled += Regex.Replace(File.ReadAllText(HttpContext.Current.Server.MapPath(file.IncludedVirtualPath)), pattern, string.Empty);
        }

        response.Content = compiled;
        response.ContentType = "text/javascript";
    }
}

然后在BundleConfig

bundles.Add(new Bundle("~/Scripts/js-bundle",  new LogRemoverTransform(), new JsMinify())
                  .Include("~/Scripts/script1.js",
                           "~/Scripts/script2.js",
                           "~/Scripts/script3.js"));

如果js文件非常大,请使用StreamReader代替File.ReadAllText()