Search code examples
javascript.netminify

Elegantly minify dynamically generated javascript in a .NET environment?


I'm programmatically creating javascript files from a .NET web app and would like to minify it before passing it to the client. Is there an efficient technique for doing this?


Solution

  • If you simply want to be able to minify a javascript string in C# before saving it to a file, I would use either the MS Ajax Minifier or the YUI compressor for .net. Both of these expose an API that allows you to do this. Here is a sample using the ajax minifier:

    var minifier = new Microsoft.Ajax.Utilities.Minifier();
    var minifiedString = minifier.MinifyJavaScript(unMinifiedString);
    

    Using the YUI Compressor for .net:

    var minifiedString = JavaScriptCompressor.Compress(unMinifiedString);
    

    Both the ajax minifier and and YUI Compressor libraries are available via Nuget.