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
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.
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.
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.
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.
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.
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.
In real time, it is good to use the second approach of compiling TypeScript code that saves a lot of time.
Views: 7296 | Post Order: 1