Using TypeScript in ASP.NET 5

By Dawid on (tags: asp.net 5, mvc, TypeScript, visual studio, vs, categories: code, web)

As we can read on the TypeScript it lets you write JavaScript the way you really want to. And guess what – you can do it in Visual Studio 2015!

Visual Studio TypeScript support two different modes:

  • File Scope: in this mode TypeScript files opened in Visual Studio Code are treated as independent units. As long as a file a.ts doesn't reference a file b.ts explicitly (either using /// references or external modules) there is no common project context between the two files.
  • Project: a TypeScript project is defined via a tsconfig.json file. The presence of such a file in a directory indicates that the directory is the root of a TypeScript project. The file itself lists the files belonging to the project as well as compiler options.

To begin your journey with TypeScript in ASP.NET 5 first you need to modify you file. In this example I will use gulp – streaming build tool built on Node.js. So you project file should contains following entries:

  • gulp – core gulp.js package
  • gulp-tsc – TypeScript compiler
  • gulp-shell – command line interface
  • run-sequence – this module allows you to run series of tasks in a sequence
  • typescript

and could looks like:

The next step which have to be done it to create main file (of course there is no problem with using Grunt). In this file we will be writing our tasks which will be used to compile TypeScript.

My file is looking like that:

The most important part of the file is build:ts task where TypeScript compiler is called using the gulp-tsc npm package. We are passing in the arguments from the source location and producing the compiled JavaScript to the destination.

There are couple of ways of calling build:ts task. We can use command line:

which you give you output similar to:

Or you can call it from VS 2015 interface using Task Runner Explorer:

 

Gulp allows you to do much more with more complex tasks, you can read more about it on it home page.  Bellow is example directories structure which can be used to handle TypeScript assets: