TypeScript Tips and Tricks

Automatically compile TypeScript files when using VS Code

If you’re writing TypeScript using Visual Studio, your files are automatically compiled when you save (assuming you haven’t turned this off…the feature is found in the Project Properties > TypeScript Build screen).

If you don’t use Visual Studio, and instead are using a lightweight IDE such as VS Code or Sublime Text, you don’t get this feature.

Manual compilation

First things first, how would you normally compile a TypeScript file to JavaScript? VS Code doesn’t do this out of the box (perhaps the will add this functionality in the future, I’m not sure). You use a task runner.

To configure a task runner, open your project that has some TypeScript files, and press Ctrl+Shift+B. A little notification to appear that tells you that no task runner is configured. Click Configure Task Runner. VS Code will create a directory called .settings and add a new JSON file called tasks.json to this directory.

Open tasks.json and inspect the default configuration (the one that isn’t commented out, VS Code will show you some other sample configurations that are commented out. Look for the following line;

"args": ["HelloWorld.ts"]

Change this path to point at a TypeScript file in your project. Save changes.

Now open your TypeScript file, and open in it in side by side view. Put the TypeScript file (.ts) on the left, and put the compiled JavaScript code (.js) on the right.

Make a change your TypeScript file and press Ctrl+Shift+B again. You should see the updated JavaScript file.

Automatic compilation

Having to press Ctrl+Shift+B every time you want to compile your TypeScript files gets really old, really fast. Lets say to make a change, you refresh your browser and the change hasn’t been applied. You open the dev tools, start debugging, and hang on…where is your code? Oh right yeah, you forgot to run the task runner. Rinse and repeat.

Instead of using a task runner to call the TypeScript compiler (tsc.exe), we can instead make tsc work for us, using the -w flag, called the watch flag.

Wrong Way

My first thoughts when trying to get this to work were to pass the -w flag to tsc using VS Code. Try opening tasks.json and changing the args option as follows;

"args": ["-w", "test.ts"],

Yeah that doesn’t work (even though other sample configurations shown in the same file pass commands to tsc in this manner).

Right Way

The best way to do this is via the command line. Open a Node.js command prompt window, and change directory (cd) to your project folder. Now run the following command;

tsc -w

This will listen for changes in the given directory, and all sub directories. Whenever a change is made, the file will be recompiled automatically. So now, pressing Ctrl+S on the keyboard will cause the file to be recompiled.

We’re almost there. If you want the file to automatically compile pretty much as you type (not quite that frequently, but almost as good), you can enable Auto Save in VS Code. Click File > Auto Save to turn it on.

Success! All your TypeScript files will be automatically saved and compiled as your work on them, with no keyboard presses needed.

I mentioned Sublime text at the beginning of this tip, because of course this isn’t a VS Code specific feature. You can easily enable this regardless of the editor you are using.

Source maps

Source maps are are means of rebuilding compiled and minified code back to its original state. When you write TypeScript, it is transpiled to JavaScript and can be minified to reduce bandwidth costs and improve page load times. This process, however, makes debugging virtually impossible due to the fact that all variable names are changed, all white-space and comments are removed etc.

Browsers use source maps to translate this code back into its original state, enabling you to debug TypeScript code straight from the dev tools. Pretty neat huh?!

Modern browsers (IE10, Chrome, Firefox) enable source maps by default.

However, I have on many occasions encountered errors and inconsistencies when using source maps, and it is not just me who is encountering these issues. The dev tools might tell me, for example, the wrong value for this. TypeScript captures the value of this in a local variable, so that, in theory, you’re always using the right this (it typically captures the instance of the class itself). Often, however, dev tools will incorrectly tell me that this is an instance of window… rendering the debugger useless.

How to turn source maps off

There are a couple of ways to approach this.

Stop generating source maps

TypeScript is generating the source maps for you.

If you are using Visual Studio, you can stop generating source maps by going to Project Properties > TypeScript Build and un-checking Generate Source Maps. Be sure to rebuild your project.

For everybody else, you simply don’t pass in the –sourcemap argument to tsc.

Disable source maps in the browser

Modern browsers have the ability to disable source maps.

Chrome
1. Open dev tools
2. Settings
3. Sources (middle column)
4. Enable JavaScript source maps

Firefox
1. Open dev tools
2. Debugger
3. Settings
4. Un-tick “Show Original Sources”

Combine output in a single file

There are a bunch of tools available to take care of bundling and minification of JavaScript files. You’ve probably used either ASP .NET Bundling & Minification, Web Essentials bundler, Uglify or something similar. These tools generally work well and I’ve only experienced minor problems with each tool. (The ASP .NET bundler is a bit more troublesome than most, to be fair).

When using a task runner such as Grunt or Gulp, you pass in an array of all the file paths you want to include in the bundle.

Example;

files: {
        'dest/output.min.js': ['src/input.js']
      }

Generally I don’t take this approach of passing in individual files, I prefer to pass in a recursive path, perhaps something like this;

"**/*.ts"

That aside, if you prefer to include your files individually in Grunt/GulpFile, TypeScript can help you out by combining all the compiled JavaScript into a single file.

Using Visual Studio

If you’re using Visual Studio, there is a simple user interface to set this up. Right click your project and select Project Properties > TypeScript Build.

Under the Output header, there are two options of interest;

  1. Combine JavaScript output into file: – Name of the file to put the merged JavaScript.
  2. Redirect JavaScript output to directory: – The folder in which to put the merged file.

Typically you would use these two in conjunction with each other. You can then modify your Grunt/GulpFile to point at the merged file, rather than all your un-merged JavaScript files.

Via command prompt

The flags you need are as follows;

--out FILENAME
--outDir DIRECTORYPATH

Available from version 1.5

Version 1.5 of the TypeScript compiler (version 1.5.3 to be precise, use the -v flag to check you aren’t using 1.5.0 beta) adds a few additional features of some use (this is not an exhaustive list);

-m KIND or –module KIND

Ok this isn’t new, but TypeScript 1.5 has added support for UMD and System, so you can now pass the name through to use that module system. There is an updated UI in Visual Studio 2015 RTM for this feature.

–noEmitOnError

Doesn’t generate any JS files if any compile time errors are detected. You might want to turn this off if you want to ignore certain errors (like, incorrect or incomplete type declaration file).

–preserveConstEnums

The default behaviour in past versions of tsc was to remove enumerations and replace them with te actual value of the enumeration.

So if your enum was;

enum DaysOfWeek{
    Monday,
    Tuesday
    ... 
}

...

console.log(DayOfWeek.Monday)

The transpiled output would be;

console.log(0 /*Monday*/)

Passing the –preserveConstEnums flag prevents this transformation from taking place, so the original code stays in act.

Summary

The TypeScript compiler is flexible and configurable and has a wealth of flags that can be passed to it to change the transpiled output. Using Node.js tools, you can easily have your TS files automatically transpiled, you can have source maps for a better debugging experience, and you can have all the transpiled TS files merged into a single file for easier uglification.

I’ll update this post with new tips and tricks as I come across them. If you ave any good ones, let me know in the comments or get me on Twitter, and I’ll update the post accordingly.

If you’re interested in learning about all the different compiler flags that TypeScript accepts, you can find them in GitHub.

ASP .NET 5 (vNext), first thoughts

Microsoft ASP .NET 5 is a major shift from traditional ASP .NET methodologies. Whilst I am not actively developing ASP .NET 5 applications at the minute, .NET has always been my bread and butter technology. When I look at industry trends here in the UK, all I see is .NET .NET .NET, therefore it is important to have one eye on the future. I’ve watched all the introduction videos on the ASP .NET website, but I also wanted to take a look at what ASP .NET 5 means to me.

This is not meant to be a fully formed post. This will come later down the line. Right now, I think ASP .NET 5 is evolving too quickly to be “bloggable” fully.

Version disambiguation and terminology

Lets take a second to disambiguate some terminology. Microsoft’s understanding of versioning has always been different to everybody else. This tweet from Todd Motto really sums it up;

Looks like versioning is not going to get any simpler for the time being

ASP .NET 5 (ASP .NET 4.6 is the current version)

Previously known as ASP .NET vNext, ASP .NET 5 is the successor of ASP .NET 4.6. In the past, versions of ASP .NET have followed the .NET Framework release cycle. It looks like that is coming to an end now. ASP .NET should not be confused with MVC. ASP .NET is a technology, MVC is a framework.

ASP .NET 5 is currently scheduled for release in the first quarter of 2016, as per this tweet from Scott Hansleman; (I suspect this date will slip though)

The ASP .NET team would rather “get it right” and take longer, than rush the product and get it wrong (which would spell long term disaster for the platform)

MVC 6

This is the new version of Microsoft’s Model-View-Controller framework. There is a nice post on StackOverflow that describes the new features of MVC 6. Here are a few of the best;

  • “Cloud optimization” … so better performance.
  • MVC, WebAPI and Web Pages are now unified.
  • Removed dependency on System.Web, which results in more an 10x reduction in request overhead.
  • Built in dependency injection, which is pluggable, so it can be switched out for other DI providers.
  • Roslyn enables dynamic compilation. Save your file, refresh the browser. Works for C# too. No compilation required.
  • Cross platform.

DNX (.NET Execution Environment)

The .NET Execution Environment, DNX, is a cross platform thing that will run your .NET applications. DNX is built around the .NET Core, which is a super lightweight framework for .NET applications, resulting in drastically improved performance thanks to a reduce pipeline. Dependency on the dinosaur assembly System.Web has gone, but in return you are restricted to more of a subset of features. This is a good thing, my friend. System.Web has every featured imagined over the last 13 years, 75% of which you probably don’t even care about.

Interesting new features and changes

  • Use of data annotations for things that would previously have been HTML helpers (Tag helpers)
  • Environment tag on _Layout. Enables a simple means to specify which resources to load depending on the application configuration (Debug mode, release mode etc)
  • Bower support
  • Gulp out of the box (interesting that they chose Gulp over Grunt, I think its Gulps superior speed that has won the day.)
  • .NET Core. Drastically reduced web pipeline, could result in 10x faster response in some cases (remains to be seen!).
  • Noticeably faster starting up.
  • Save to build. With Roslyn, it is now not necessary to build every time you make a change to a CSharp (.cs) code file. Just save and refresh. Compilation is done in memory.
  • Intellisense hints that assembly is not available in .NET Core (nice!)
  • Built in dependency injection, which can be switched out for a third party mechanism.
  • Web API is now no longer a separate component. Web API was originally a separate technology from MVC. The two were always very alike, and it makes sense that the two should be merged together.

Deleted stuff

  • Web.config has finally been removed and exchanged for a simpler JSON formatted file. Parties have been thrown for less.
  • packages.config has gone, seems redundant now that things are in line with how the rest of the web develop, i.e. using package.json

Bad points

  • Still heavy use of the Viewbag in default projects. I’d like to see the ViewBag removed entirely, but I suspect that will never happen.
  • The default project template is still full of “junk”, although it is now a bit simpler to tidy up. Visual Studio automatically managers bower and npm packages, so removing a package is as simple as deleting it from the package.json file.

Summary

I am very keen to get cracking with ASP .NET 5 (vNext), although at the time of writing I feel that it still a little bit too dynamic to start diving in to at a deep level. The introduction of .NET Core, a cross platform, open source subset of the .NET framework is awesome… I can’t wait to see the benefits of using this in the wild (reduced server costs!!! especially when running on a Linux based machine, although it remains to be seen). The ViewBag still exists, but we can’t have it all I suppose.

At this point, we’re at least 5-6 months away from a release, so develop with it at your own risk!

Using Gulp-SASS with VS Code task runner

With the task runner built in to VS Code, you can set up Gulp to automatically compile your SASS files to CSS with a simple key press.

VS Code task runner prerequisites

To be able to get this working, you need the following prerequisites

To install Gulp run the following command;

npm install -g gulp

or

npm install gulp --save-dev

To install into your development environment. I’d generally recommend installing gulp globally as you will likely be using it a lot.

You will probably want to install gulp-sass locally in your dev environment. We will get to that shortly.

Existing Project

If you are using an existing project and you already have a Gulp file (GulpFile.js) and a package.json file, feel free to skip the next step.

New Project

Create a new folder for your project, open VS Code and click File > Open Folder. Point to your new folder and click OK.

Open a Node.JS command prompt, and change directory to your new folder.

Now type the following command;

npm init

As shown here;

npm init

You will be prompted to enter details about your project. Either accept the default by pressing Enter or enter the details as appropriate. This will generate a package.json file for your project.

Configure the task runner

The quickest, easiest way to configure the task runner is to press Ctrl+Shift+B and click the Configure Task Runner button.

Configure Task Runner

VS Code will switch to a file called tasks.json. This file contains several possible configurations depending on what you want to do.

Ensure that all configurations are commented out, then all the following configuration;

{
    "version": "0.1.0",
    "command": "gulp",
    "isShellCommand": true,
    "tasks": [
        {
            "taskName": "sass",
            "isBuildCommand": true,
            "showOutput": "silent"
        }
    ]
}

This will execute gulp, and will run the sass task (which we haven’t defined yet).

GulpFile.js

Either open or create a new file called GulpFile.js, at the root of your project.

If you just created a new GulpFile, add the following JavaScript;

'use strict';

var gulp = require('gulp');
var sass = require('gulp-sass');

gulp.task('sass', function () {
  gulp.src('*.scss')
    .pipe(sass().on('error', sass.logError))
    .pipe(gulp.dest('./'));
});

gulp.task('sass:watch', function () {
  gulp.watch('*.scss', ['sass']);
});

or if you are editing an existing configuration, note that you don’t need to re-import Gulp.

Note: For simplicity, this configuration assumes that your SASS files are in the root of your project. In most cases, this will not be true.

If, for example, your SCSS files are contained in a folder called Content, you might use the following path instead;

./Content/**/*.scss

The same applies to the destination folder, as defined by;

gulp.dest('./')

Ensure this path is appropriate to your project structure.

npm install

To install Gulp into your development environment, go back to package.json and add the devDependencies section as shown below;

"devDependencies": {
    "gulp": "~3.9.0",
    "gulp-sass": "~2.0.4"
  }

Your final package.json file may look something like this;

{
  "name": "test",
  "version": "1.0.0",
  "description": "",
  "main": "gulpfile.js",
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "gulp": "~3.9.0",
    "gulp-sass": "~2.0.4"
  }
}

Go back to the Node.JS command prompt and type the following command;

npm install

This will create a new folder in your project called node_modules, which will in turn contain each dependency.

Compiling the SCSS files

Add a new SCSS file to your project and add some dummy CSS;

body { }

Now with everything set up, press the Ctrl+Shift+B keyboard combination to kick off the task.

Task Finished

If all goes well, the corresponding CSS files should be compiled for you.

Summary

VS Code has a very powerful and versatile task runner built in that can be configured to run just about any task. We have created a GulpFile, and told VS Code how to run Gulp and which tasks to execute, using the tasks.json configuration file. In this case we have configured the Gulp-SASS npm package, but there are no limitations on what packages you can use. You can also add multiple tasks that do just about anything.

Finally…

If you encounter any problems, let me know via the comments section below, or via Twitter and I’ll be more than happy to help you out.

Why Visual Studio 2015 has changed my life

I’ve been using Visual Studio on an almost daily basis since 2002. Before that, my development tool of choice was Visual Basic 6 (Visual Studio 6). The shift between those two versions felt like using a whole new product at the time. Since then, changes to Visual Studio have been incremental. Microsoft have released a new version every 2-3 years. Visual Studio 2015, however, feels like another significant paradigm shift.

The point of this post is not to outline all the shiny new features, there are official blog posts for that. No. I wanted to tell you how the changes to Visual Studio have directly changed the way I work on a day to day basis.

Visual Studio Tasks (Task Runner Explorer)

The wider web development community has been using task runners, GruntJS and more recently GulpJS, for at least the last few years.

On every project I work on these days, I use TypeScript and SASS. Web essentials previously was responsible for compiling my SASS files, as well as providing linting for both SASS and TypeScript. With the 2015 release, this functionality has been removed. There are a bunch of Mads Kristensen extensions on Visual Studio Gallery that you can install that will add this functionality back in.

However, why not cut out the middle man and set up these tasks yourself?

With tasks you can;
* Automatic SASS/SCSS compilation using Ruby gem (and a watcher that “listens” for changes to files as you make them)
* SCSS and TypeScript Linting, with your own linting configuration files directly in the project (perfect for sharing with team members)
* Better bundling and minification. You can use something like UglifyJS instead of the old ASP .NET bundler (which was horribly buggy!)
* But most importantly, the door is open to a world of possibility.

Tasks enable you to automate tedious repetitive tasks and share those efficiencies easily with your team, whilst not restricting you to a particular subset of tools.

Reduced dependence on ReSharper

I’ve been a fan of ReSharper for a long time and I’ve even blogged about why I can’t work without it. All this said, however, its truth time. I don’t want to have to depend on a third party tool to make my IDE more useful. I want Visual Studio to be awesome enough on its own that I don’t have to install any third party tools to make it usable.

ReSharper introduced the lightbulb menu several major versions ago. The lightbulb menu introduces many code refactorings, such as implement interface, refactor this, and so many I can hardly think. The newly introduced native lightbulb menu in Visual Studio 2015 adds some nice refactorings.

Unfortunately, Visual Studio 2015 doesn’t go quite far enough in this respect, hence why the section is named Reduced dependence on ReSharper. I do expect this feature to get a lot of attention during this release, assuming that the open source community can tap into it easily enough.

Lambda Expressions

Lambda expressions and LINQ were introduced in version 3.0 of the .NET Framework, roughly 8 years ago. Debugging support for lambda expressions was non existent in the first versions, and was incrementally improved over time.

To start off with, you couldn’t debug any method that contained a lambda expression. Not only that, but if any method in the call stack contained a lambda expression, even if your method did not contain a lambda expression, you couldn’t use edit and continue.

Then a subsequent release solved this problem, you could still not edit and continue a method that contained a lambda expression, but the call stack problem was gone.

Now with Visual Studio 2015, you get the full debugging experience. You can edit methods that contain lambda expressions, and you can edit lambda expressions directly, and edit & continue in the same way you could with any other code before. This is a major time-saver.

You’ve never been able to add watches or use the immediate window to debug lambda expressions. With Visual Studio 2015, this is no longer the case. Rejoice.

Summary

Visual Studio has introduced the task runner explorer, which can run tasks on various IDE events (Open, before/after build etc.). This really opens the door to “the rest of the web development world”, where sophisticated tooling exists to automate mundane tasks such as bundling, linting, pre/post processing and so much more. Developers are no longer tied to doing things the Visual Studio way. Other enhancements such as the lightbulb menu and better debugging will save developers time and reduce dependence on third party tooling.

Gulp in Visual Studio

This post walks through the basics of using Gulp in Visual Studio 2013. Specifically, we will add two compile time tasks; one for linting TypeScript files, and another for linting SCSS. You are not limited to using just linters with Gulp, in fact you can do just about anything.

Gulp is specifically good at running repetitive tasks and is widely used in the non-.NET world via the command line. Other common tasks include; minification, compilation and running unit tests. Fortunately for us, some unofficial tools have been developed by Microsoft (specifically, the awesome Mads Kristensen and his dedicated team) which enable us to use Gulp directly inside Visual Studio.

Gulp is JavaScript configuration based, meaning you configure Gulp via a special file called GulpFile.js, which you add to your project.

This post specifically targets Visual Studio 2013, because at the time of writing Visual Studio 2015 hasn’t been released yet (its actually RC at this point). As Microsoft tooling is evolving rapidly at this time, i’ll avoid covering 2015 for now (however, I may revise this post after Visual Studio 2015 is released).

This post is a fork of the popular post Grunt In Visual Studio 2013.

Prerequisites

NodeJS and npm

Gulp is built on top NodeJS and is installed via the Node Package Manager (npm). Both of these tools need to be installed to use Gulp. Check that you already have NodeJS installed, and/or download the latest version. The installation is a trivial process, so I wont document it fully here, but please ensure that the “npm package manager” feature is installed. This feature is selected by default, and it is need to install Gulp (and indeed, any other package).

Gulp

Before we can use Gulp, we must install it globally.

Open a command prompt and type

npm install -g gulp

You might want to get reacquainted with running commands in this way because with the rapid state of change in the industry, development of visual tools is always going to lag behind (even with Microsoft’s new rapid development and deployment ethos, but that’s a whole other discussion).

Task Runner Explorer

This tool will run our Gulp tasks for us. It will parse our Gulp File (which we will create shortly), list our tasks, let us run our tasks individually, and let us bind our tasks to “IDE events” (pre-build, after build, clean & solution open).

To install Task Runner Explorer, go to Tools > Extensions and Updates and type Task Runner Explorer. The first result should by created by Microsoft Corp.

Task Runner Explorer

Task Runner Explorer

Local Gulp

Now that we have the necessary tooling installed, we need to add Gulp to our actual project (and any additional packages we want to use). Packages are controlled using a special file called package.json. This file contains metadata about your project, and the packages its dependent on (and potentially a bunch of other stuff that is out of the scope of this tutorial).

Create a file called package.json at the root of your project, and add the following code;

{
    "name": "Gulp101",
    "version": "1.0.0",
    "devDependencies": {
        "gulp": "~3.9.0",
        "gulp-scss-lint": "~0.2.1",
        "gulp-tslint": "~3.1.0-beta"
    }
}

The file is pretty self explanatory, but if you want a little more information with regards to versioning, see this useful post; Node and npm Version Numbering: Guide and Best Practices.

To save time later, I have also included the other development dependencies. In this case, our TypeScript linter (gulp-tslint) and SCSS linter (gulp-scss-lint). We will configure these shortly.

To install the dependencies, open a command prompt and change the directory to that which contains your newly created package.json and run the following command;

npm install

This will result in a new directory being created, called node_modules, which will contain each dependency.

GulpFile.js

As previously mentioned, Gulp is a JavaScript based task runner. Gulp is configured/controlled using a file called Gulpfile.js. This file is responsible for defining the configuration for each task. You can have many tasks and many aliased groups that run multiple tasks.

For this tutorial we are going to validate our TypeScript and SCSS code quality using linters. Specifically, Gulp has packages called Gulp-TSLint and Gulp-SCSS-Lint (you defined and installed these packages earlier).

Add the following configuration;

var gulp = require('gulp');

var scsslint = require('gulp-scss-lint');
gulp.task('scss-lint', function () {
    gulp.src('/stuff/*.scss')
      .pipe(scsslint());
});

var tslint = require('gulp-tslint');
gulp.task('tslint', function () {
    return gulp.src('stuff/*.ts')
      .pipe(tslint())
      .pipe(tslint.report('verbose'));
});

gulp.task('typescript', ['scss-lint', 'tslint']);

Again, the beauty of Node and Gulp especially is that its pretty simple to understand what’s going on, even for a beginner.

SCSS Lint Task

The minimum configuration required is the path to your SCSS files, using the src method. In the given example, we simply find all the files in a sub directory with the extension *.scss. You can make this more complicated, and recursive, as follows;

Content/**/*.scss

This will recursively find every SCSS file in all folders sitting below the Content folder.

There’s a comprehensive tutorial on how to further refine the configuration on the NPM website. The documentation on GitHub is also excellent.

TS Lint Task

Before you can lint a TypeScript file, you must define some rules that you want to enforce throughout your code-base. You can push this configuration to source control and share with your team for maximum consistency.

If you have Web Essentials installed (and I highly recommend all web developers install this excellent tool) then you can quickly generate a configuration file by clicking Web Essentials > Edit Global TSLint Settings (tslint.json). Clicking this drops a tslint.json file into your Documents folder and opens it directly in Visual Studio, where you can make edits. I highly recommend closing the file, moving it into your solution folder, and adding it as part of your project for easy access later.

If you don’t use Web Essentials are you insane? you can grab a sample configuration file directly from the GitHub source code repository and again I recommend that you add it as part of your project. I won’t go into the ins and outs of each of the TypeScript linting rules, that’s for another time. Just know that you can change them to your hearts content.

As with the SCSS linter, you specify the path of your TypeScript files using the src method. You pass in a string that represents the path of your TypeScript files.

gulp.src('stuff/*.ts')

Final Steps

Add some code

There is just one more step we need to take before running our tasks, we need some code to test!

Add a new SCSS file to your project, and a new TypeScript file. Add the following beautifully written ugly code to the TypeScript file;

module SomeModule {

    export class SomeClass {

        str: string;

        constructor() {
            this["str"] = "Hello, World"
        }
    }
}

The main issues with this code are trailing whitespace, no "use strict", missing semi-colons and access to a property via a string literal. We will let Gulp tell us about these shortly.

Open the task runner

Open the task runner by going to View > Other Windows > Task Runner Explorer.

Select your project (if it is not selected by default) and click the refresh button. Your Gulpfile.js configuration file should be loaded and the alias tasks and individual tasks should be displayed.

You can manually run a task (or set of tasks) by right clicking and selecting Run. If all went well, you should see the following output;

c:\Users\jon.preece\Documents\Visual Studio 2013\Projects\gulp\gulp> cmd.exe /c gulp -b "c:\Users\jon.preece\Documents\Visual Studio 2013\Projects\gulp\gulp" --color --gulpfile "c:\Users\jon.preece\Documents\Visual Studio 2013\Projects\gulp\gulp\gulpfile.js" typescript
[13:48:21] Using gulpfile c:\Users\jon.preece\Documents\Visual Studio 2013\Projects\gulp\gulp\gulpfile.js
[13:48:21] Starting 'scss-lint'...
[13:48:21] Finished 'scss-lint' after 5.33 ms
[13:48:21] Starting 'tslint'...
[13:48:21] [gulp-tslint] error (no-string-literal) helloworld.ts[8, 18]: object access via string literals is disallowed
[13:48:21] [gulp-tslint] error (semicolon) helloworld.ts[8, 41]: missing semicolon
[13:48:21] [gulp-tslint] error (use-strict) helloworld.ts[1, 1]: missing 'use strict'
[13:48:21] 'tslint' errored after 68 ms
[13:48:21] Error in plugin 'gulp-tslint'
Message:
    Failed to lint: helloworld.ts[8, 18]: object access via string literals is disallowed, helloworld.ts[8, 41]: missing semicolon, helloworld.ts[1, 1]: missing 'use strict'.
Process terminated with code 1.

Success! Wait what? Oh yes, the task has failed because our TypeScript file has lots of linting errors. Open up the TypeScript file and use the output message to fix each problem. Once done re-run the task again by right clicking and clicking run. Once all issues are resolved, you should get the following;

c:\Users\jon.preece\Documents\Visual Studio 2013\Projects\gulp\gulp> cmd.exe /c gulp -b "c:\Users\jon.preece\Documents\Visual Studio 2013\Projects\gulp\gulp" --color --gulpfile "c:\Users\jon.preece\Documents\Visual Studio 2013\Projects\gulp\gulp\gulpfile.js" typescript
[13:49:12] Using gulpfile c:\Users\jon.preece\Documents\Visual Studio 2013\Projects\gulp\gulp\gulpfile.js
[13:49:12] Starting 'scss-lint'...
[13:49:12] Finished 'scss-lint' after 5.36 ms
[13:49:12] Starting 'tslint'...
[13:49:12] Finished 'tslint' after 64 ms
[13:49:12] Starting 'typescript'...
[13:49:12] Finished 'typescript' after 7.33 μs
Process terminated with code 0.

Bindings

Right clicking and clicking run is a little too manual for my liking, this is an automation tool isn’t it? Alas, the Task Runner Explorer provides you with Bindings. Basically you can hook in to events in the IDE and run your tasks automatically when one of events happens.

Available bindings;

  • Before Build
  • After Build
  • Clean
  • Solution Open

To bind a task to a binding, right click the task (or again, the aliased task) and select Bindings > {An IDE Event of your choice}. In my case, I have chosen Before Build. So when I press Ctrl+Shift+B the tasks are ran automatically.

Note that as far as I know, you can’t fail the build if a task fails at this point. No doubt this is an upcoming feature.

Summary

Gulp is a brave new world for most .NET developers. Tooling is certainly in its infancy (within Visual Studio) at this point, but the awesome power of NodeJS, npm and Gulp can be harnessed with some useful extensions.