Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / programming / tools

Csminify: A Merge/Minifier for C# Source

4.56/5 (3 votes)
29 Aug 2019CPOL2 min read 12.2K   229  
Easily create single source file drop-ins from multiple C# source files

Introduction

I've badly wanted a more reliable, easier to use tool than ILMerge for statically linking code modules in .NET, but failing that, I'd like another way to make the equivalent of "static libraries" for common code where a separate assembly is not justified or simply not wanted, or where you wish to augment functionality using partial classes.

This tool is a command line utility that allows you to merge and minify multiple source files into a code "brick" - basically an opaque file that adds functionality to your code.

That way, you can include some code and all its file dependencies into one easy to manage file that you can simply drop into your projects.

Note: You might be asking, why minify the source code? Well, a lot of the code I use is machine generated, with deeply nested arrays, and those arrays are serialized with quite a bit of whitespace, leading to files that are sometimes 20,000 lines long or more. Minification can reduce them by an order of 10 in terms of lines, and a significant amount of KB in terms of space. This actually makes it easier on source editors, when you go to open it in something like Visual Studio. It's not easier to edit the source of course, but you shouldn't be editing these files anyway, but rather the originals.

As part of the merging process, the tool moves all usings and #defines to the top of the file, and removes duplicates. It also adds #defines for each filename, for example:

C#
#define MYFILE_CS

is declared if "myfile.cs" is included as one of the merged files. This allows for conditional compilation depending on which other files are included. That way, different files can be "aware" of each other and include code to augment the other code (usually with a partial class) accordingly. This mechanism provides the potential for complex interdependencies between source files.

Using the Tool

Simply give the names of the files to merge and minify to the utility and it spits the result to stdout.

csminify "foo.cs" "bar.cs" > "baz.cs"

This will take foo.cs and bar.cs and merge/minify them, and write the result to baz.cs.

History

  • 28th August, 2019 - Initial submission

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)