Check out our new training course on AngularJS for Flex Developers

Compile Code on the Fly - TypeScript and Gulp - Part 2

This is the second in a series of articles no compiling TypeScript applications with Gulp. Check out Part 1 which covers most of the setup; or sign up below to get our fully detailed white paper.

Gulp allows us to automatically run a gulp task when a certain directory changes. This is built in and we don't need an additional plugin to make it happen. We're going to make a task which will watch for TypeScript files for changes, and then trigger the buildTS task again.

First, let's create a variable to point at the TypeScript source:

var typeScriptSource = [sourceRoot + "/**/*.ts"];

The sourceRoot variable was created in the previous article, and points to the src directory. The wild cards tell Gulp to look at all subdirectories inside the sourceRoot folder.

Now create a gulp task called buildWatch:

gulp.task('buildWatch', ['buildTS'], function(){

You'll notice that there are three arguments to this gulp task, something we hadn't seen before. The first is the task name, buildWatch. The second is an array of strings with each string represents a gulp task. These tasks will run before the third argument's function is executed. Here we are only running one task, buildTS, before starting the buildWatch task.

Here is the function code:,['buildTS']).on('change', function(event){
console.log('Event Type' + event.type);
console.log('File Path' + event.path);

We use the watch() function on the Gulp object. It accepts two arguments. The first argument is a source array, in this case the typeScriptSource value. The second argument is a task array. In this case just the buildTS task. Reading this in English, it says watch for files that match typeScriptSource, and when something changes run the buildTS task. Dot notation is used to daisy chain an 'on' method to the watch. When the change event occurs, the type of event and modified files are output to the console.

Run this script:

gulp buildWatch

You'll see something like this:

The important thing to notice is that the console does not go back to a command prompt; the code is left running in the background. Change some code to see what happens:

As you save files, the script automatically notices, and reruns the appropriate task. You'll get console information about the file that has changed.

Overall, I find the watch task to be a very powerful development tool.

Yes, I want to get your white paper on building TypeScript applications

Related Blog Entries

Comments (Comment Moderation is enabled. Your comment will not appear until approved.)
All Content Copyright 2005, 2006, 2007, 2008, 2009 Jeffry Houser. May not be reused without permission
BlogCFC was created by Raymond Camden. This blog is running version