Automatically Compiling TypeScript in Visual Studio

After a bit of experimenting with TypeScript, I found two ways to automatically compile .ts to .js so far.

The first way is to create a project of type “HTML Application with TypeScript” and edit your TypeScript files there. Compiling the project will automatically generate the corresponding JavaScript files.

The advantage of this approach is that all your TypeScript code is kept in a separate project from your ASP.Net or ASP.Net MVC project.

But how do you get the compiled JavaScript files into your web project?

One solution is to set the project’s output directory to the script directory of your web project, and in Configuration Manager define the build order to build the TypeScript project before the web project.

For this method to work, the .js files generates by the TypeScript project must be included in the web project to be published.

But how does the TypeScript project know how to invoke the tsc compiler for .ts files? Well, it says so in the .csproj file by defining a BeforeBuild target:

<Target Name="BeforeBuild">
  <Exec Command="&quot;$(PROGRAMFILES)\Microsoft SDKs\
     TypeScript.8.0.0\tsc&quot; @(TypeScriptCompile 
     ->'&quot;%(fullpath)&quot;', ' ')" />

If you copy this block to your web project’s .csproj file (unload project, edit project, reload project), it should make your existing project compile .ts files before invoking the regular C# build.

An answer on SO also suggest an extension that compiles on save, but this only works in VS 2012.

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 )

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.