Installing TypeScript on Ubuntu Desktop

In this post I will share how to install TypeScript and Gulp.

Note: this post is a part of the series of posts about my experience using Ubuntu Desktop for software development.

 

Prerequisites

For TypeScript and Gulp to work they require Node and NPM installed on your machine. Follow these steps to install Node and NPM on Ubuntu Desktop.

 

TypeScript

You install TypeScript by installing typescript npm package globally.

$ sudo npm install -g typescript

To check the TypeScript compiler version type

$ tsc --version

blog-22-01

This is the minimum you need to do to install TypeScript and start using it.

 

Example

Let’s create a small application to see how we can use TypeScript compiler. I’m going to create the following three files in ~/src/calculator directory.

interface CalculatorInterface {
    add(a: number, b: number): number;
}
/// <reference path="CalculatorInterface.ts" />

class Calculator implements CalculatorInterface {
    public add(a: number, b: number): number {
        return a + b;
    }
}
/// <reference path="Calculator.ts" />

let calc: CalculatorInterface = new Calculator();
let result: number = calc.add(2, 3);

console.log(`The result is ${result}`);

blog-22-02

To compile these three files and bundle them in a single file type

$ tsc --outFile bundle.js main.ts

blog-22-03

And to finally run our calculator, type

$ nodejs bundle.js

Remember, that on Ubuntu you should use nodejs command, not node.

blog-22-04

If you are curious how bundle.js looks like – here it is:

blog-22-05

Let’s make our example a bit more interesting. Let’s add a web page and display the results of calculation on it. Add index.html and modify main.ts.

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8" />
        <title>TypeScript Calculator</title>
    </head>
    <body>
        <h3>TypeScript Calculator</h3>
        <p />
        <div id="result">Loading...</div>
        <script src="bundle.js"></script>
    </body>
</html>
/// <reference path="Calculator.ts" />

let calc: CalculatorInterface = new Calculator();
let result: number = calc.add(2, 3);

let element = document.getElementById("result");
element.innerText = `The result is ${result}`;

Let’s use VS Code for the rest of the example. Make sure you are in ~/src/calculator directory and type (it is “code”, then “space”, then “dot”)

$ code .

blog-22-06

Then type already familiar command to compile TypeScript into JavaScript and then start HTTP Server and open your browser at http://localhost:8080

$ tsc --outFile bundle.js main.ts
$ hs

blog-22-07

This is the most primitive way to develop web applications using TypeScript. And I’d suspect nobody develops this way. Ideally you should use task runners, like Grunt or Gulp, to automate compilation, bundling and minification at the bare minimum. Let’s look at how Gulp can help us.

 

Gulp

Gulp is a task runner that definitely will enhance your workflow. There are tons of npm packages/plugins that you can use to create your own workflow that suits your needs. Let’s look at how we can compile, bundle and minify our TypeScript/JavaScript code.

First, install Gulp CLI npm package globally

$ sudo npm install -g gulp-cli

Then create two directories – src and dist and move all source code to src (you can delete bundle.js).
blog-22-08

Then, initialize your project directory (~/src/calculator)

$ npm init

Note that for entry point you should use ./dist/main.js

blog-22-09

Then turn ~/src/calculator directory into TypeScript project by creating a tsconfig.json file by typing

$ tsc --init

blog-22-10

{
    "compilerOptions": {
        "module": "commonjs",
        "target": "es5",
        "noImplicitAny": false,
        "sourceMap": false
    },
    "exclude": [
        "node_modules"
    ]
}

Then install dependencies (npm packages) by typing:

$ npm install --save-dev gulp browserify tsify vinyl-source-stream gulp-uglify vinyl-buffer gulp-sourcemaps
{
  "name": "calculator",
  "version": "1.0.0",
  "description": "an example application",
  "main": "./dist/main.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "Dmitry Zinchenko",
  "license": "ISC",
  "devDependencies": {
    "browserify": "^13.1.0",
    "gulp": "^3.9.1",
    "gulp-sourcemaps": "^1.6.0",
    "gulp-uglify": "^2.0.0",
    "tsify": "^1.0.4",
    "vinyl-buffer": "^1.0.0",
    "vinyl-source-stream": "^1.1.0"
  }
}

Then start VS Code and add the following gulpfile.js

var gulp = require("gulp");
var browserify = require("browserify");
var source = require('vinyl-source-stream');
var tsify = require("tsify");
var uglify = require('gulp-uglify');
var sourcemaps = require('gulp-sourcemaps');
var buffer = require('vinyl-buffer');
var paths = {
    pages: ['src/**/*.html']
};

var brfy = browserify({
    basedir: '.',
    debug: true,
    entries: ['src/main.ts'],
    cache: {},
    packageCache: {}
}).plugin(tsify);

gulp.task("copy-html", function () {
    return gulp
        .src(paths.pages)
        .pipe(gulp.dest("dist"));
});

function bundle() {
    return brfy
        .bundle()
        .pipe(source('bundle.js'))
        .pipe(buffer())
        .pipe(sourcemaps.init({loadMaps: true}))
        .pipe(uglify())
        .pipe(sourcemaps.write('./'))
        .pipe(gulp.dest("dist"));
}

gulp.task("default", ["copy-html"], bundle);

Then modify CalculatorInterface.ts, Calculator.ts and main.ts to add export and import statements

export interface CalculatorInterface {
    add(a: number, b: number): number;
}
import { CalculatorInterface } from "./CalculatorInterface";

export class Calculator implements CalculatorInterface {
    public add(a: number, b: number): number {
        return a + b;
    }
}
import { CalculatorInterface } from "./CalculatorInterface";
import { Calculator } from "./Calculator";

let calc: CalculatorInterface = new Calculator();
let result: number = calc.add(2, 3);

let element = document.getElementById("result");
element.innerText = `The result is ${result}`;

Now in ~/src/calculator directory run gulp command

blog-22-11

And then in ~/src/calculator/dist run HTTP server

blog-22-12

And finally open your browser at http://localhost:8080

blog-22-13

At this point, every time you modify TypeScript code – you only have to run gulp command once again.

And this is how your bundled and minified JavaScript looks like

blog-22-14

 

Watchify

You can use Watchify to start Gulp and keep it running to incrementally compile your changes. For that we need to install two more npm packages.

$ npm install --save-dev watchify gulp-util
{
  "name": "calculator",
  "version": "1.0.0",
  "description": "an example application",
  "main": "./dist/main.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "Dmitry Zinchenko",
  "license": "ISC",
  "devDependencies": {
    "browserify": "^13.1.0",
    "gulp": "^3.9.1",
    "gulp-sourcemaps": "^1.6.0",
    "gulp-uglify": "^2.0.0",
    "gulp-util": "^3.0.7",
    "tsify": "^1.0.4",
    "vinyl-buffer": "^1.0.0",
    "vinyl-source-stream": "^1.1.0",
    "watchify": "^3.7.0"
  }
}

Then you need to modify your gulpfile.js

var gulp = require("gulp");
var browserify = require("browserify");
var source = require('vinyl-source-stream');
var watchify = require("watchify");
var gutil = require("gulp-util");
var tsify = require("tsify");
var uglify = require('gulp-uglify');
var sourcemaps = require('gulp-sourcemaps');
var buffer = require('vinyl-buffer');
var paths = {
    pages: ['src/**/*.html']
};

var watchedBrowserify = watchify(browserify({
    basedir: '.',
    debug: true,
    entries: ['src/main.ts'],
    cache: {},
    packageCache: {}
}).plugin(tsify));

gulp.task("copy-html", function () {
    return gulp.src(paths.pages)
           .pipe(gulp.dest("dist"));
});

function bundle() {
    return watchedBrowserify
        .bundle()
        .pipe(source('bundle.js'))
        .pipe(buffer())
        .pipe(sourcemaps.init({loadMaps: true}))
        .pipe(uglify())
        .pipe(sourcemaps.write('./'))
        .pipe(gulp.dest("dist"));
}

gulp.task("default", ["copy-html"], bundle);
gulp.watch("src/**/*.html", ["copy-html"]);
watchedBrowserify.on("update", bundle);
watchedBrowserify.on("log", gutil.log);

Start Gulp by typing

gulp

Now, the only thing you need to do is to make changes to your .ts or .html files, refresh browser and you will see changes.

blog-22-15

blog-22-16

blog-22-17

Installing TypeScript on Ubuntu Desktop

One thought on “Installing TypeScript on Ubuntu Desktop

Comments are closed.