Merge and Minify as Visual Studio Build Tasks

During development, a web project typically contains several JavaScript and CSS files.

Current best practice is to merge these files into single files (.js and .css respectively) and minify the merged files to reduce the number of requests between client and web server.

This can be achieved using two MSBuild tasks:

To invoke the tasks, you need to edit your web project’s .csproj file. Either open it in a text editor, or from Visual Studio, unload the project, and edit the project file while the project is unloaded from the solution.

First, you need to register both tasks in the csproj file (insert right before the </Project> tag at the end of the file):

<Import Project="$(MSBuildExtensionsPath32)\Microsoft\MicrosoftAjax\ajaxmin.tasks" />
<Import Project="path\to\FrogMSBuild\FrogMSBuild.tasks" />

MS Ajax Minifier comes with an installer, and installs itself under the Program Files\MSBuild directory. FrogMSBuild can simply be copied to a directory of your choice.

The tasks run after build:

<Target Name="AfterBuild">

Define the JavaScript files to be merged:

    <Scripts_Frog_JSFile Include="Scripts\foo.js;Scripts\bar.js;Scripts\etc.js;" />

Invoke the FileCombinator task defined in FrogMSBuild:

  <FileCombinator SourceFiles="@(Scripts_Frog_JSFile)" 
    CombinationMode="Javascript" RemoveSourceFiles="false" />

Define the JavaScript files to be minified:

    <JS Include="Scripts\Merged.js" Exclude="**\*.min.js" />

Invoke the Minification task

  <AjaxMin JsSourceFiles="@(JS)" 
    JsSourceExtensionPattern="\.js$" JsTargetExtension=".min.js" />
<!-- CssSourceFiles="@(CSS)" 
  CssSourceExtensionPattern="\.css$" CssTargetExtension=".min.css" / -->

This example deals with JavaScript only.

Load the web project again in Visual Studio, and the next build will generate merged and minified .js and .css files.

2 Responses to Merge and Minify as Visual Studio Build Tasks

  1. micaleel says:

    Nice tip man. Thanks!

  2. FrogMSBuild is no longer available from your link.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: