Reputation: 6573
My current bundle config concatenates all the script files and minifies it and generates a single file.but is not removing the console.log lines from the js files,how to add configuration to remove console.log() lines from the files.my current config setting is
bundles.Add(
new Bundle(
"~/Scripts/js-bundle",
new IBundleTransform[] {new JsMinify() }).Include(
"~/Scripts/script1.js",
"~/Scripts/script2.js",
"~/Scripts/script3.js"))
I tried adding LogRemoverTransform() but i am getting some error
Upvotes: 0
Views: 1187
Reputation: 35222
You need to create your own Bundle Transformation
, by implementing IBundleTransform
. You can use this regex (borrowed from this question) to get the instances of console.log
, console.info
etc and replace them with empty strings.
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";
}
}
And then in your BundleConfig
:
bundles.Add(new Bundle("~/Scripts/js-bundle", new LogRemoverTransform(), new JsMinify())
.Include("~/Scripts/script1.js",
"~/Scripts/script2.js",
"~/Scripts/script3.js"));
If the js
files are very big, use StreamReader
instead of File.ReadAllText()
.
Upvotes: 4