TypeScript and Building with your Visual Studio Project

TypeScript is great, and it is in Preview from Microsoft.  One of the first issues I had was how to get TypeScript to build your JavaScript files every time you build your Visual Studio project.

Steps to achieve this:

  1. Open your project file using editor (so you can see the xml definition)
  2. Search for import of Microsoft.Common.targets tag
         <Import Project=”$(MSBuildBinPath)\Microsoft.Common.targets” />
  3. If you have not found this reference in your project include it, it can be added after <Project *>
    This will enable for you to have BeforeBuild and AfterBuild events.
<Target Name="AfterBuild">
        <Message Text="After Build" Importance="high" />
<Target Name="BeforeBuild">  
        <Message Text="Before Build" Importance="high" />  

Put following xml under first PropertyGroup. This will introduce variables that we are using later on.Note: make sure you have correct version of typescript installed


Now we are ready to introduce our implementation.The following can be inserted in Project tag, its best to add it in the end of the file.

<Project ToolsVersion="4.0" DefaultTargets="Build"    xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<!-- omitted code -->
<!-- Insert your implementation -->
Following tag will get all files from project directory that ends with .ts
 <TypeScriptCompile Include="$(ProjectDir)\**\*.ts" />
Update before build event to call our custom target

<Target Name="BeforeBuild">  
  <Message Text="Before Build" Importance="high" />  
  <CallTarget Targets="TypeScriptBuild"/>

And our implementation of build for every TypeScript build for every single file.

<Target Name="TypeScriptBuild"  Inputs="@(TypeScriptCompile)" Outputs="%
    (Identity).Dummy" Condition="'$(CompileTypeScript)'=='true'" >
 <Message Text="Building typescript file - @(TypeScriptCompile)"  Importance="high" />  
<Exec Command=""$(MSBuildProgramFiles32)\Microsoft SDKs\TypeScript\$(TypeScriptVersion)\tsc" -target ES5 "@(TypeScriptCompile)"" />

Thanks for Pavel Svarc for find this out