/// <summary> /// Minifies the specified resource. /// </summary> /// <param name="resource">The resource.</param> /// <returns> /// The minified resource. /// </returns> public override string Minify(string resource) { JavaScriptMinifier minifier; if (this.Options.Minify) { minifier = new JavaScriptMinifier { VariableMinification = VariableMinification.LocalVariablesAndFunctionArguments }; } else { minifier = new JavaScriptMinifier { VariableMinification = VariableMinification.None, PreserveFunctionNames = true, RemoveWhiteSpace = false }; } string result = minifier.Minify(resource); if (this.Options.CacheFiles) { this.AddItemToCache(this.Options.MinifyCacheKey, result); } return(result); }
/// <summary> /// Runs the JavaScript minifier on the content. /// </summary> public static IAsset MinifyJavaScript(this IAsset asset, CodeSettings settings) { var minifier = new JavaScriptMinifier(settings); asset.Processors.Add(minifier); return(asset); }
public void Test() { string js = JavaScriptMinifier.Minify(@"if (Test.Ajax( 5 ) == 1) { alert( 'x' ); } "); Assert.AreEqual("\nif(Test.Ajax(5)==1){alert('x');}\n", js); }
public void ProcessRequest(HttpContext context) { this.context = context; HttpRequest request = context.Request; // Read setName, version from query string string setName = request["s"] ?? string.Empty; string version = request["v"] ?? string.Empty; // Decide if browser supports compressed response bool isCompressed = this.CanGZip(context.Request); // If the set has already been cached, write the response directly from // cache. Otherwise generate the response and cache it if (!this.WriteFromCache(setName, version, isCompressed)) { using (MemoryStream memoryStream = new MemoryStream(8092)) { // Decide regular stream or gzip stream based on whether the response can be compressed or not //using (Stream writer = isCompressed ? (Stream)(new GZipStream(memoryStream, CompressionMode.Compress)) : memoryStream) using (Stream writer = isCompressed ? (Stream)(new ICSharpCode.SharpZipLib.GZip.GZipOutputStream(memoryStream)) : memoryStream) { // Read the files into one big string StringBuilder allScripts = new StringBuilder(); foreach (string fileName in GetScriptFileNames(setName)) { allScripts.Append(File.ReadAllText(context.Server.MapPath(fileName))); } // Minify the combined script files and remove comments and white spaces var minifier = new JavaScriptMinifier(); string minified = minifier.Minify(allScripts.ToString()); // Send minfied string to output stream byte[] bts = Encoding.UTF8.GetBytes(minified); writer.Write(bts, 0, bts.Length); } // Cache the combined response so that it can be directly written // in subsequent calls byte[] responseBytes = memoryStream.ToArray(); context.Cache.Insert(GetCacheKey(setName, version, isCompressed), responseBytes, null, System.Web.Caching.Cache.NoAbsoluteExpiration, CACHE_DURATION); // Generate the response this.WriteBytes(responseBytes, isCompressed); } } }
public async Task MinifyJs_EmptyContent_Success(string input) { var minifier = new JavaScriptMinifier(new CodeSettings()); var context = new Mock <IAssetContext>().SetupAllProperties(); context.Object.Content = new Dictionary <string, byte[]> { { "", input.AsByteArray() } }; var options = new Mock <WebOptimizerOptions>(); await minifier.ExecuteAsync(context.Object); Assert.Equal("", context.Object.Content.First().Value.AsString()); Assert.Equal("", minifier.CacheKey(new DefaultHttpContext())); }
public async Task MinifyJs_CustomSettings_Success() { var settings = new CodeSettings { TermSemicolons = true }; var minifier = new JavaScriptMinifier(settings); var context = new Mock <IAssetContext>().SetupAllProperties(); context.Object.Content = new Dictionary <string, byte[]> { { "", "var i = 0;".AsByteArray() } }; var options = new Mock <WebOptimizerOptions>(); await minifier.ExecuteAsync(context.Object); Assert.Equal("var i=0;", context.Object.Content.First().Value.AsString()); Assert.Equal("", minifier.CacheKey(new DefaultHttpContext())); }
private string CompressFile(string file) { string outputFileName = Path.GetTempPath() + Path.GetRandomFileName(); var minifier = new JavaScriptMinifier(); minifier.Minify(file, outputFileName); try { string output; using (var sr = new StreamReader(outputFileName)) { output = sr.ReadToEnd(); } return output; } finally { File.Delete(outputFileName); } }
public static string GetJsCodeByFile(string f) { string jscode = ""; StreamReader sr = new StreamReader(Utils.GetMapPath("/public/js/" + f + ".js"), System.Text.UTF8Encoding.UTF8); JavaScriptMinifier jss = new JavaScriptMinifier(); string sw = ""; try { jss.Minify(sr.ReadToEnd(), out sw); jscode = sw; } finally { jss = null; sr.Close(); sr.Dispose(); } return(jscode); }
private string CompressFile(string file) { string outputFileName = Path.GetTempPath() + Path.GetRandomFileName(); var minifier = new JavaScriptMinifier(); minifier.Minify(file, outputFileName); try { string output; using (var sr = new StreamReader(outputFileName)) { output = sr.ReadToEnd(); } return(output); } finally { File.Delete(outputFileName); } }
/// <summary> /// Minifies the specified resource. /// </summary> /// <param name="resource">The resource.</param> /// <returns> /// The minified resource. /// </returns> public override string Minify(string resource) { JavaScriptMinifier minifier; if (this.Options.Minify) { minifier = new JavaScriptMinifier { VariableMinification = VariableMinification.LocalVariablesAndFunctionArguments }; } else { minifier = new JavaScriptMinifier { VariableMinification = VariableMinification.None, PreserveFunctionNames = true, RemoveWhiteSpace = false }; } return(minifier.Minify(resource)); }
/// <summary> /// Minifies the provided script /// </summary> /// <param name="script">Script to minify</param> /// <returns>Minified script</returns> private static string RunJsMin(string script) { return(JavaScriptMinifier.Minify(script)); }
public void ProcessRequest(HttpContext __context) { this.context = HttpContextFactory.Current; var request = context.Request; var response = context.Response; response.Clear(); if (TMConfig.Current.TMDebugAndDev.Enable302Redirects && send304Redirect()) { context.Response.StatusCode = 304; context.Response.StatusDescription = "Not Modified"; return; } setCacheHeaders(); try { minifyCode = true; ignoreCache = true; if (request.QueryString["Hello"] == "TM") { response.Write("Good Morning"); return; } // Read setName, version from query string setName = XssEncoder.UrlEncode(request.QueryString["s"]) ?? string.Empty; version = XssEncoder.UrlEncode(request.QueryString["v"]) ?? string.Empty; if (setName == string.Empty) { response.Write("//nothing to do"); return; } if (request.QueryString["dontMinify"] == "true") { minifyCode = false; } switch (request.QueryString["ct"]) { case "css": this.contentType = "text/css"; minifyCode = false; break; default: this.contentType = "application/x-javascript"; break; } // Decide if browser supports compressed response bool isCompressed = this.CanGZip(context.Request); using (MemoryStream memoryStream = new MemoryStream(8092)) { // Decide regular stream or gzip stream based on whether the response can be compressed or not //using (Stream writer = isCompressed ? (Stream)(new GZipStream(memoryStream, CompressionMode.Compress)) : memoryStream) using (Stream writer = isCompressed ? (Stream)(new ICSharpCode.SharpZipLib.GZip.GZipOutputStream(memoryStream)) : memoryStream) { // Read the files into one big string this.allScripts = new StringBuilder(); this.filesProcessed = GetScriptFileNames(setName); foreach (string fileName in this.filesProcessed) { var fullPath = context.Server.MapPath(fileName.trim()); if (fullPath.fileExists()) { this.allScripts.AppendLine("\n\n/********************************** "); this.allScripts.AppendLine(" ***** " + fileName); this.allScripts.AppendLine(" **********************************/\n\n"); this.allScripts.AppendLine(File.ReadAllText(fullPath)); } } var codeToSend = this.allScripts.ToString(); if (minifyCode) { // Minify the combined script files and remove comments and white spaces var minifier = new JavaScriptMinifier(); this.minifiedCode = minifier.Minify(codeToSend); codeToSend = this.minifiedCode; } // Send minfied string to output stream byte[] bts = Encoding.UTF8.GetBytes(codeToSend); writer.Write(bts, 0, bts.Length); } // Generate the response byte[] responseBytes = memoryStream.ToArray(); this.WriteBytes(responseBytes, isCompressed); } } catch (Exception ex) { ex.log(); response.Write("//Error processing request" + ex.Message); response.End(); } }
/// <summary> /// /// </summary> /// <param name="request"></param> /// <param name="response"></param> public void Compress(HttpRequest request, HttpResponse response) { Encoding encoding = Encoding.GetEncoding("windows-1252"); string enc, cacheFile = null, cacheKey = null, content = ""; StringWriter writer = new StringWriter(); byte[] buff = new byte[1024]; GZipOutputStream gzipStream; bool supportsGzip; // Set response headers response.ContentType = "text/javascript"; response.Charset = this.charset; response.Buffer = false; // Setup cache response.Cache.SetExpires(DateTime.Now.AddSeconds(this.ExpiresOffset)); // Check if it supports gzip enc = Regex.Replace("" + request.Headers["Accept-Encoding"], @"\s+", "").ToLower(); supportsGzip = enc.IndexOf("gzip") != -1 || request.Headers["---------------"] != null; enc = enc.IndexOf("x-gzip") != -1 ? "x-gzip" : "gzip"; // Setup cache info if (this.diskCache) { cacheKey = ""; foreach (JSCompressItem item in this.items) { // Get last mod if (item.Type == JSItemType.File) { DateTime fileMod = File.GetLastWriteTime(request.MapPath(item.Value)); if (fileMod > this.lastUpdate) this.lastUpdate = fileMod; } cacheKey += item.Value; } cacheKey = this.cacheFileName != null ? this.cacheFileName : MD5(cacheKey); if (this.gzipCompress) cacheFile = request.MapPath(this.cacheDir + "/" + cacheKey + ".gz"); else cacheFile = request.MapPath(this.cacheDir + "/" + cacheKey + ".js"); } // Use cached file disk cache if (this.diskCache && supportsGzip && File.Exists(cacheFile) && this.lastUpdate == File.GetLastWriteTime(cacheFile)) { if (this.gzipCompress) response.AppendHeader("Content-Encoding", enc); response.WriteFile(cacheFile); return; } foreach (JSCompressItem item in this.items) { if (item.Type == JSItemType.File) { if (!File.Exists(request.MapPath(item.Value))) { writer.WriteLine("alert('Could not load file: " + StringUtils.Escape(item.Value) + "');"); continue; } StreamReader reader = new StreamReader(File.OpenRead(request.MapPath(item.Value)), System.Text.Encoding.UTF8); if (item.RemoveWhiteSpace) { JavaScriptMinifier jsMin = new JavaScriptMinifier(reader, writer); jsMin.Compress(); } else { writer.Write('\n'); writer.Write(reader.ReadToEnd()); writer.Write(";\n"); } reader.Close(); } else { if (item.RemoveWhiteSpace) { JavaScriptMinifier jsMin = new JavaScriptMinifier(new StringReader(item.Value), writer); jsMin.Compress(); } else { writer.Write('\n'); writer.Write(item.Value); writer.Write('\n'); } } } content = writer.ToString(); // Generate GZIP'd content if (supportsGzip) { if (this.gzipCompress) response.AppendHeader("Content-Encoding", enc); if (this.diskCache && cacheKey != null) { try { // Gzip compress if (this.gzipCompress) { gzipStream = new GZipOutputStream(File.Create(cacheFile)); buff = encoding.GetBytes(content.ToCharArray()); gzipStream.Write(buff, 0, buff.Length); gzipStream.Close(); File.SetLastWriteTime(cacheFile, this.lastUpdate); } else { StreamWriter sw = File.CreateText(cacheFile); sw.Write(content); sw.Close(); File.SetLastWriteTime(cacheFile, this.lastUpdate); } // Write to stream response.WriteFile(cacheFile); } catch (Exception) { content = "/* Not cached */" + content; if (this.gzipCompress) { gzipStream = new GZipOutputStream(response.OutputStream); buff = encoding.GetBytes(content.ToCharArray()); gzipStream.Write(buff, 0, buff.Length); gzipStream.Close(); } else { response.Write(content); } } } else { content = "/* Not cached */" + content; gzipStream = new GZipOutputStream(response.OutputStream); buff = encoding.GetBytes(content.ToCharArray()); gzipStream.Write(buff, 0, buff.Length); gzipStream.Close(); } } else { content = "/* Not cached */" + content; response.Write(content); } }
/// <summary> /// Strips the whitespace from any .js file. /// </summary> /// <param name="body">The body text of which to remove white space from.</param> /// <returns>The specified body with no white space.</returns> public static string RemoveWhiteSpaceFromJavaScript(string body) { JavaScriptMinifier jsmin = new JavaScriptMinifier(); return(jsmin.Minify(body)); }
public void ProcessRequest(HttpContext __context) { this.context = HttpContextFactory.Current; var request = context.Request; var response = context.Response; response.Clear(); if (TMConfig.Current.TMDebugAndDev.Enable302Redirects && send304Redirect()) { context.Response.StatusCode = 304; context.Response.StatusDescription = "Not Modified"; return; } setCacheHeaders(); try { minifyCode = true; ignoreCache = true; if (request.QueryString["Hello"]=="TM") { response.Write("Good Morning"); return; } // Read setName, version from query string setName = XssEncoder.UrlEncode(request.QueryString["s"]) ?? string.Empty; version = XssEncoder.UrlEncode(request.QueryString["v"]) ?? string.Empty; if (setName ==string.Empty) { response.Write("//nothing to do"); return; } if (request.QueryString["dontMinify"] == "true") minifyCode = false; switch(request.QueryString["ct"]) { case "css": this.contentType = "text/css"; minifyCode = false; break; default: this.contentType = "application/x-javascript"; break; } // Decide if browser supports compressed response bool isCompressed = this.CanGZip(context.Request); using (MemoryStream memoryStream = new MemoryStream(8092)) { // Decide regular stream or gzip stream based on whether the response can be compressed or not //using (Stream writer = isCompressed ? (Stream)(new GZipStream(memoryStream, CompressionMode.Compress)) : memoryStream) using (Stream writer = isCompressed ? (Stream)(new ICSharpCode.SharpZipLib.GZip.GZipOutputStream(memoryStream)) : memoryStream) { // Read the files into one big string this.allScripts = new StringBuilder(); this.filesProcessed = GetScriptFileNames(setName); foreach (string fileName in this.filesProcessed) { var fullPath = context.Server.MapPath(fileName.trim()); if (fullPath.fileExists()) { this.allScripts.AppendLine("\n\n/********************************** "); this.allScripts.AppendLine(" ***** " + fileName); this.allScripts.AppendLine(" **********************************/\n\n"); this.allScripts.AppendLine(File.ReadAllText(fullPath)); } } var codeToSend = this.allScripts.ToString(); if (minifyCode) { // Minify the combined script files and remove comments and white spaces var minifier = new JavaScriptMinifier(); this.minifiedCode = minifier.Minify(codeToSend); codeToSend = this.minifiedCode; } // Send minfied string to output stream byte[] bts = Encoding.UTF8.GetBytes(codeToSend); writer.Write(bts, 0, bts.Length); } // Generate the response byte[] responseBytes = memoryStream.ToArray(); this.WriteBytes(responseBytes, isCompressed); } } catch(Exception ex) { ex.log(); response.Write("//Error processing request"+ ex.Message); response.End(); } }
public void ProcessRequest(HttpContext __context) { this.context = HttpContextFactory.Current; var request = context.Request; var response = context.Response; response.Clear(); try { minifyCode = true; ignoreCache = true; if (request.QueryString["Hello"]=="TM") { response.Write("Good Morning"); return; } // Read setName, version from query string setName = XssEncoder.UrlEncode(request.QueryString["s"]) ?? string.Empty; version = XssEncoder.UrlEncode(request.QueryString["v"]) ?? string.Empty; if (setName ==string.Empty) { response.Write("//nothing to do"); return; } if (request.QueryString["dontMinify"] == "true") minifyCode = false; switch(request.QueryString["ct"]) { case "css": this.contentType = "text/css"; minifyCode = false; break; default: this.contentType = "application/x-javascript"; break; } // Decide if browser supports compressed response bool isCompressed = this.CanGZip(context.Request); // If the set has already been cached, write the response directly from // cache. Otherwise generate the response and cache it if (ignoreCache || !this.WriteFromCache(setName, version, isCompressed)) { using (MemoryStream memoryStream = new MemoryStream(8092)) { // Decide regular stream or gzip stream based on whether the response can be compressed or not //using (Stream writer = isCompressed ? (Stream)(new GZipStream(memoryStream, CompressionMode.Compress)) : memoryStream) using (Stream writer = isCompressed ? (Stream)(new ICSharpCode.SharpZipLib.GZip.GZipOutputStream(memoryStream)) : memoryStream) { // Read the files into one big string this.allScripts = new StringBuilder(); this.filesProcessed = GetScriptFileNames(setName); foreach (string fileName in this.filesProcessed) { var fullPath = context.Server.MapPath(fileName.trim()); if (fullPath.fileExists()) { this.allScripts.AppendLine("\n\n/********************************** "); this.allScripts.AppendLine(" ***** " + fileName ); this.allScripts.AppendLine(" **********************************/\n\n"); this.allScripts.AppendLine(File.ReadAllText(fullPath)); } } var codeToSend = this.allScripts.ToString(); if (minifyCode) { // Minify the combined script files and remove comments and white spaces var minifier = new JavaScriptMinifier(); this.minifiedCode = minifier.Minify(codeToSend); codeToSend = this.minifiedCode; } // Send minfied string to output stream byte[] bts = Encoding.UTF8.GetBytes(codeToSend); writer.Write(bts, 0, bts.Length); } // Cache the combined response so that it can be directly written // in subsequent calls byte[] responseBytes = memoryStream.ToArray(); context.Cache.Insert(GetCacheKey(setName, version, isCompressed), responseBytes, null, System.Web.Caching.Cache.NoAbsoluteExpiration, CACHE_DURATION); // Generate the response this.WriteBytes(responseBytes, isCompressed); } } } catch(Exception ex) { ex.log(); response.Write("//Error processing request"+ ex.Message); response.End(); } }
/// <summary> /// Compile JS. /// </summary> private static void CompileJS() { if (config.Automations == null) { return; } foreach (var automation in config.Automations.Where(a => a.Type.ToLower() == "js")) { if (automation.WaitBeforeParsing > 0) { Thread.Sleep(automation.WaitBeforeParsing); } if (automation.fswEntries == null) { continue; } var js = string.Empty; var af = new List <string>(); foreach (var entry in automation.fswEntries) { var files = GetFiles( entry.Path, entry.Pattern); foreach (var file in files) { if (af.Contains(file)) { continue; } af.Add(file); } } js += GetFileContents(af); if (automation.ParseTags) { js = ReplaceTags(js); } try { if (automation.Minify) { js = new JavaScriptMinifier().Minify(js); } } catch { Console.WriteLine("Could not minify JS"); } var cc = compiledContent .SingleOrDefault(c => c.TagName == automation.TagName); if (cc == null) { cc = new CompiledContent { TagName = automation.TagName, Type = automation.Type }; compiledContent.Add(cc); } cc.Content = js; cc.LastCompile = DateTime.Now; var path = automation.DestFile; if (string.IsNullOrWhiteSpace(path)) { continue; } var pathIsAbs = path.Substring(1, 1) == ":" || path.StartsWith("\\"); if (!pathIsAbs) { path = Path.Combine( configPath, path); } try { File.WriteAllText( path, js); } catch { Console.WriteLine("Could not write JS to dest file {0}", automation.DestFile); } } }
private string MinifyScript(string script) { JavaScriptMinifier jsm = new JavaScriptMinifier(); return jsm.Minify(script); }