Typescript > Introduction

Compiling TypeScript code in Typescript

How to compile TypeScript code to JavaScript?


In the previous post, we learnt how to Install TypeScript. In this post, we shall learn how to compile the TypeScript code to generate JavaScript code.

There are two ways to compile the TypeScript code

1. Compile TypeScript code Using Visual Studio Command prompt

After downloading the TypeScript, we should have the TypeScript command line compiler tsc.exe. So open the Developer Command Prompt for VS2015 from the Start menu of the Windows Operating System as shown in the picture below.

Visual studio command prompt

Now create a  sample .ts file with the following code, we have named it as DataTypes.ts

// declare boolean type
var isTrue = false;

// declare number type
var myAge = 10;

// declare string type
var fullName = "Sheo Narayan";

Above code snippet, simply declare boolean, integer and string variable. We shall learn about this in forthcoming posts.

Now go to the Developer Command prompt and navigate to the folder where we have created the .ts file and run tsc DataTypes.ts command as shwon in the picture below.

Compiling TypeScript code using command prompt

If everything goes right, after few seconds, we should see a DataTypes.js file as shown in the left side of the above picture.

The output of the file DataTypes.js looks like below.

// declare boolean type
var isTrue = false;

// declare number type
var myAge = 10;

// declare string type
var fullName = "Sheo Narayan";

This approach looks simple however, it's little pain to every time go to the compile time and compile the code. So we have another simpler approach to compile the TypeScript code.

2. Compile TypeScript code Using Visual Studio while saving

The other and very simpler approach is using Visual Studio itself. This is much much simpler as when you modify the TypeScript file (.ts) and save it, Visual Studio compiles this code for you and generate corresponding JavaScript code automatically.

To setup this configuration, go to Tools menu of the Visual Studio like shown below.

Tools menu of Visual Studio 2015

Now from the left side panel, select Text Editor and then go to TypeScript > Project. Now check the chekbox "Automatically compile TypeScript files which are not part of a project" and click OK.

Automatically compile TypeScript file

Now as soon as you hit the Save icon of Visual Studio toolbar or press Ctrl+S to save the TypeScript file, you see the JavaScript file gets generated automatically. In below, picture you can see that I have kept both .ts and .js file side by side so that I can see what is happening while I am pressing Save.

JavaScript output of TypeScript code

In real time, it is good to use the second approach of compiling TypeScript code that saves a lot of time.

 Views: 1330 | Post Order: 1



Write for us