IMG-LOGO

Minify Javascript, CSS, and HTML Files Tool

andy - 12 Jan, 2019 2066 Views 0 Comment

I create a simple console application that will minify the files like javascript, CSS and HTML files. I found it useful and I hope the source code and the application can be shared and used especially if you develop web applications and do not use an automated process like CLI (Command Line Tools) such as Uglify, Webpack, Grunt, Gulp etc. Back days, most developers still use online tools to compress their files. But if you prefer automated, this little console application might also help. This little console application still in initial development. So if you find any bug or issue feel free to modify it and share it with bytutorial.com community.

The console application will read the settings value from a setting.config file. It will have three settings which are listed and explained below.

1. SourceDirectories

This setting is used to determined the location of the files that you want to minify. You can specify more than 1 location path.

2. FilePatterns

This setting is used to what types of file extensions you want to include in minification process.

3. IgnoreFileNames

This setting is used to ignore or skip any files. Sometimes when you develop web applications, some of the javascript or CSS libraries may have already been minified. So this setting is handy to exclude those files.

The concept of this console application is pretty simple. It basically will get the files based on the source of directory you provide and using the built in .Net framework to perform the search of the files pattern. It will use the GetFiles function. I created another blog article about this function, you can check it out by clicking this link.

Here is the console application code. It uses the .Net Regular Expression to remove any comments and new line or tabs that are not needed when minifying a file.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

namespace bytutorial.com.minifier
{
    class Program
    {
        private static List<string> sourceDirectories = new List<string>();
        private static string ignoreFileNames = "";
        private static string minifyFiles = "";
        private static string filePatterns = "";

        static void Main(string[] args)
        {
            //get the configuration files
            GetSettingValues();
        }


        //Method to getting the settings value from setting.config file
        static void GetSettingValues()
        {
            try
            {
                XmlDocument doc = new XmlDocument();
                string xmlText = System.IO.File.ReadAllText(AppDomain.CurrentDomain.BaseDirectory + "/setting.config");
                doc.LoadXml(xmlText.Substring(xmlText.IndexOf(Environment.NewLine)));
                XmlNode nodeParent = doc.SelectSingleNode("/configuration");
                if (nodeParent != null)
                {
                    XmlNodeList childNodes = nodeParent.ChildNodes;
                    foreach (XmlNode node in childNodes)
                    {
                        switch (node.Name)
                        {
                            case "SourceDirectories":
                                XmlNodeList sourceDirectoryNodes = node.ChildNodes;
                                foreach (XmlNode dbNode in sourceDirectoryNodes)
                                {
                                    sourceDirectories.Add(dbNode.InnerText);
                                }
                                break;
                            case "Settings":
                                XmlNodeList settingNodes = node.ChildNodes;
                                foreach (XmlNode nodeSetting in settingNodes)
                                {
                                    switch (nodeSetting.Name)
                                    {
                                        case "FilePatterns":
                                            filePatterns = nodeSetting.InnerText;
                                            break;
                                        case "IgnoreFileNames":
                                            ignoreFileNames = nodeSetting.InnerText;
                                            break;
                                    }
                                }
                                break;
                        }
                    }
                }

                //show the configuration summary settings
                WriteLine(">>> Configuration settings have been read successfully.");
                WriteLine(">>> File Patterns: " + filePatterns);
                WriteLine(">>> Ignore Files: " + ignoreFileNames);

                //empty line
                WriteLine("");

                ignoreFileNames = "," + ignoreFileNames + ",";
                List<FileInfo> allFiles = new List<FileInfo>();

                foreach (string dir in sourceDirectories)
                {
                    //single extension only
                    if (filePatterns.IndexOf(",") == -1)
                    {
                        AddFiles(allFiles, dir, minifyFiles);
                    }
                    else
                    {
                        string[] patternArray = filePatterns.Split(',');
                        foreach (string filePattern in patternArray)
                        {
                            AddFiles(allFiles, dir, filePattern);
                        }
                    }

                }

                int minifyCounter = 0;
                foreach (FileInfo file in allFiles)
                {
                    if (ignoreFileNames.IndexOf("," + file.Name.ToLower() + ",") == -1)
                    {
                        //Read the content of the file
                        string text = System.IO.File.ReadAllText(file.FullName);

                        //re-write back the minify content to the same file name
                        using (StreamWriter writetext = new StreamWriter(file.FullName, false))
                        {
                            StringBuilder sb = new StringBuilder();
                            writetext.Write(Utils.minifyContent(text, file.Extension.ToLower() == ".html"));
                        }

                        //Show the minified file
                        WriteLine("Minify File: " + file.FullName);

                        //Add the minify counter
                        minifyCounter++;
                    }
                }
                ReadLine("Total minify files: " + minifyCounter.ToString() + (minifyCounter > 1 ? " files." : " file."));
            }
            catch (Exception ex)
            {
                WriteLine(">>> Error reading configuration: " + ex.Message.ToString());
            }
        }

        //Method to add files
        static void AddFiles(List<FileInfo> allFiles, string directoryPath, string extension)
        {
            FileInfo[] files = Utils.GetFiles(directoryPath, extension);
            if (files.Count() > 0)
            {
                foreach (FileInfo objFile in files)
                {
                    allFiles.Add(objFile);
                }
            }
        }

        //Method to write console line
        static void WriteLine(string message)
        {
            Console.WriteLine(message);
        }

        //Method to read console line
        static void ReadLine(string message = "")
        {
            WriteLine(message);
            Console.ReadLine();
        }
    }
}

This is a sample setting.config file information.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <SourceDirectories>
    <Directory>C:\mywebsite</Directory>
  </SourceDirectories>
  <Settings>
    <FilePatterns>*.css,*.js,*.html</FilePatterns>
    <IgnoreFileNames>jquery.min.js,libs.min.js</IgnoreFileNames>
  </Settings>
</configuration>

There are more improvements needed on this application such as checking whether the settings information have been provided or whether the settings are correct, or maybe even in minifying the file process, etc. Feel free to improve it and hopefully it will be useful for your development journey.

When coding your javascript files, I recommend you to close your variable declaration properly with semicolon as this might cause the minification to fail when you try to run your web application.

Download Files

You can download the files on the following link.

Download

How to use this minify console application?

In the zip file, under the bin/release folder, there is an executable file. You can double click this executable files to run the program. Before running this console program. Make sure you check the config setting and ensure the directory path exists.

See below an example of the console application screenshot when the minification process is completed.

Comments

There are no comments available.

Write Comment
0 characters entered. Maximum characters allowed are 1000 characters.

Popular Articles

Popular Web Tools

Word Sorter Online

Use our free alphabetical order tool to sort words or texts in ascending or descending order.