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> 


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

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

<PropertyGroup>  
<TypeScriptVersion>0.8.1.1</TypeScriptVersion>
<CompileTypeScript>true</CompileTypeScript>
  </PropertyGroup> 


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


Following tag will get all files from project directory that ends with .ts


<ItemGroup> 
 <TypeScriptCompile Include="$(ProjectDir)\**\*.ts" />
</ItemGroup> 

Update before build event to call our custom target
<Target Name="BeforeBuild">
  <Message Text="Before Build" Importance="high" />
  <CallTarget Targets="TypeScriptBuild"/>
</Target>

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;" />
</Target>
 
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:

  





No comments:

Post a Comment