Thursday, August 23, 2018

Minify js file using Microsoft.Ajax.Utilities.Minifier (c# / .NET)


Apart from inbuilt bundling and minification in MVC we might sometimes need to minify javascript files. You can get 'AjaxMin' from nuget and use it to compress the js file. 


string sourceDirectoryPath = @"C:\sourceFile.js";
string destinationDirectoryPath = @"C:\destinationFile.js";

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

var minifiedJSString = minifier.MinifyJavaScript(System.IO.File.ReadAllText(sourceDirectoryPath));

System.IO.File.WriteAllText(destinationDirectoryPath, minifiedJSString);

This code will fetch the source js file from source directory path, minify the text and save it to the destination directory path.