BrunoLM BrunoLM - 1 year ago 89
C# Question

How to compress Javascript files using C#?

I've found Dean Edward's lib for .NET on his website. This is almost what I want, but that was made for .NET 1.1 and there isn't an option to shrink variables.

I want to know how can I implement in C# a way to minify Javascript files and also shrink variables...

How can I achieve it?

Answer Source

Based on Ilya Volodin answer I found Microsoft Ajax Minifier

Using the DLL I can just call

(new Minifier()).MinifyJavaScript(source);

And it will return the minified script, more details about this here. That is exactly what I was looking for. It also has a StyleMinifier that is a big plus!

I made one console application to minify and combine javascript files. This can be used on Post Builds...

static void Main(string[] args)
    if (args == null || (args != null && args.Length < 2))
        Console.WriteLine("Usage: jsmin <file1[,file2,fileN]> <outfile>");

    var argc = args.Length;

    if (File.Exists(args[argc - 1]))
        if (File.GetAttributes(args[argc - 1]) == FileAttributes.ReadOnly)
            File.SetAttributes(args[argc - 1], FileAttributes.Normal);

    using (var sw = new StreamWriter(args[argc - 1]))
        for (var i = 0; i < argc - 1; ++i)
            string source = String.Empty;
                source = File.ReadAllText(args[i]);
            catch (IOException)
                Console.WriteLine("File \"{0}\" was not found.", args[i]);

            sw.WriteLine((new Minifier()).MinifyJavaScript(source));
            /* css */
            //sw.WriteLine((new Minifier()).MinifyStyleSheet(source, new CssSettings { ColorNames = CssColor.Hex }));


jsmin <file1[,file2,fileN]> <outfile>


jsmin jquery-1.4.4.js jquery.min.js
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download