How to Minify Your JavaScript and CSS File

Minifying your JavaScript and CSS files is now very easy. Just a single-click installation and when you build your web application it's converted automatically to a minified file.

Download the Microsoft Ajax Minifier from https://github.com/microsoft/ajaxmin.

After successful installation of the Microsoft Ajax Minifier, open your project in Visual Studio.

You can see your .js and .css files are not minified.

JVCSS1.gif

The Ajax Minifier supports both ASP.NET Web Forms and ASP.NET MVC Web Application Projects (WAPs). But, you cannot use the minifier with ASP.NET Web Forms Websites.

In Visual Studio, select the menu option Tools, Options, Projects and Solutions. Check the check box labeled "Always show solution".

JVCSS2.gif

Now build your project and unload your project.

JVCSS3.gif

Edit in .csproj file add before </Project>

<Target Name="BeforeBuild">
  </Target>
  <Target Name="AfterBuild">
  </Target>
  <Import Project="$(MSBuildExtensionsPath)\Microsoft\MicrosoftAjax\ajaxmin.tasks" />
  <Target Name="AfterBuild">
    <ItemGroup>
      <JS Include="**\*.js" Exclude="**\*.min.js;Scripts\*.js" />
    </ItemGroup>
    <ItemGroup>
      <CSS Include="**\*.css" Exclude="**\*.min.css" />
    </ItemGroup>
    <AjaxMin JsSourceFiles="@(Scripts)" JsSourceExtensionPattern="\.js$" JsTargetExtension=".min.js" CssSourceFiles="@(Styles)" CssSourceExtensionPattern="\.css$" CssTargetExtension=".min.css" />
</Target>

@(Scripts) and @(Styles) folder of JavaScript and CSS file. And reload the project and build it.


Similar Articles