BrunoLM BrunoLM - 1 month ago 19
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

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>");
        return;
    }

    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;
            try
            {
                source = File.ReadAllText(args[i]);
            }
            catch (IOException)
            {
                Console.WriteLine("File \"{0}\" was not found.", args[i]);
                continue;
            }

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

Syntax:

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

Example:

jsmin jquery-1.4.4.js jquery.min.js
Comments