我当前的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()但是我收到了一些错误
答案 0 :(得分:1)
您需要通过实施Bundle Transformation
来创建自己的IBundleTransform
。您可以使用this regex(borrowed from this question)获取console.log
,console.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()
。