Monday, 31 December 2012

TypeScript MSBuild as part of project file

I have wrote article how to build typescript using msbuild file.
Now I have wanted to run it as part of my project, so every time the project file is build, the msbuild gets executed.

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" />

Now we need to add our specific implementation of msbuild actions.
I have decided that I want to implement my build in before build event.

Now I needed to include condition, in case that I do not want to run this compile every time.

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="">
<!-- 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="&quot;$(MSBuildProgramFiles32)\Microsoft SDKs\TypeScript\$(TypeScriptVersion)\tsc&quot; -target ES5 &quot;@(TypeScriptCompile)&quot;" />
And after this just reload the project file and build the project.
In output window in Show output from : Option Build you will be able to find: