Friday 25 September 2015

Writing Gulpfile using TypeScript

Lately, I have been using Gulp a lot at my work and also in the demos of my articles. I also use TypeScript quite often these days while playing with Angular 2. While using Gulp to transpile TypeScript to JavaScript using Gulp, I got thought to use TypeScript itself to write the gulpfile as well. It might sound a bit weird as we use Gulp to transpile the files to JavaScript and the gulpfile itself has to be converted by someone into JavaScript before any other task runs. Thanks to npm scripts, we have a way to achieve this.

The scripts section of the package.json file can be used to register commands and these commands can be executed from command prompt of any OS using the “npm run” command. For instance, if we have the following configuration saved in scripts section of package.json file:

"scripts": {
  "setup" : "npm install && bower install"
}

We can run the command “npm run setup” from the command prompt. This command would install all Node.js dependencies and the bower dependencies. We can transpile the gulpfile using this section and then combine this command with a command to run a task. For this, we need to have TypeScript installed globally. This can be done using the following command:

> npm install –g typescript

To write the gulpfile using TypeScript and take advantage of the type checking system, we need to get the type definition files. Type definitions for the gulpfile are available on tsd. Following command gets the type definitions for the gulpfile:

> tsd install gulp --save

These files are saved inside typings folder of the project. To make our lives easier, the tsd command creates a type definition file that refers to all of the installed type definitions. This file is tsd.d.ts inside the typings folder.

Now, we need to refer the tsd.d.ts file in the gulpfile.ts file and start writing Gulp tasks. Following snippet shows a task that concatenates all JavaScript files:

/// <reference path="typings/tsd.d.ts" />

var gulp = require('gulp'),
    concat = require('gulp-concat');

gulp.task('default', function(){
  return gulp.src(["scripts/*.js"])
    .pipe(concat("combined.js"))
    .pipe(gulp.dest("dist"));
});

This example is a simple one. In more advanced scenarios, we can use types as well.

To run this gulp task, we need to define a command in the scripts section to transpile the file and then run the task. Following is the command:

"scripts": {
  "concat": "tsc gulpfile.ts && gulp"
}

All is done. We can now run this command as follows:

> npm run concat

Happy coding!

No comments:

Post a Comment

Note: only a member of this blog may post a comment.