AngularJS 1.x with Typescript – 1

Everyone knows TypeScript especially after AngularJS team starts using Typescript to build AngularJS 2.0. I have been trying to avoid Typescript, since it is a transcompiler and the underlying language is still relevant and powerful. But over the holidays I spend some time learning Typescript with in the realm of AngularJS and found it interesting and easy to use. It reminds me of C# in many ways. With majority of developers are in Java or .Net world, because of Typescript, more people will be able to move to front end development easily.

When I was learning Angular first time, I wrote series blogs to educate myself and for anyone interested in following. So with that same spirit, I am going to do the same for AngularJS development with Typescript.

Couple of things;

  • This series is only for Angular 1.x not Angular 2.0
  • I am more interested in AngularJS so, I will not go deep into Typescript.
  • For development I am using Visual Studio Code. It is a free idea with good support to Typescript.
  • I use Win 10 desktop for development.
  • Instead of building a large application I will be focusing on concepts and sample example specific to concept.

 

Today we will setup our development environment and write a simple hello world program.

  1. Install Node/NPM

First and foremost, we need to install Node, even though we will not use node right away the npm tool that comes with Node we will use it to bring in the packages. So go to https://nodejs.org/en/ and download and install Node.

2. Install TypeScript

Open a command prompt and where ever you are, type in the following to install TypeScript.

npm install -g typescript

It doesn’t matter which directory you are in, since we are passing ‘-g’, TypeScript compiler will be available globally.

Once TypeScript installed, verify you have the latest version. by running following command

tsc -v

You should see version result as 1.7 or greater. If you have older version then you might have VS 2013/2015 installed and it already have old TypeScript in your path that you need to remove.

3. Install Visual Studio Code (Skip if you have a favorite editor)

Go to Visual Studio Code home page, download and install the editor.

4. Install TypeScript Definition Manager (TSD)

Before we start coding, we need to add intellisense to our editor. To do that, we need to install type script definition manager. Once TSD installed, similar to npm which can install the packages available under npm, we can use tsd to bring in the definition files of all javascript files we will use. For now think of it is a way to bring intellisense to the editor.

Fortunately TSD is available through npm so we install TSD once globally so we do not need to do it again and again like TSC.

npm install -g tsd

Once it is installed we will see how to bring the definition files during the development of the Hello World program.

 

Lets write some code:

On to developing Hello world program in AngularJS/TypeScript. Since we are using Visual Studio Code (VCS), I am going to open a command prompt and create a directory to build our hello world program.

I created a folder blog1 under c:\users\unni\learningangularts\.  Open VSC and use open folder option to point to the directory we created. It will create a empty editor with no files in it.

To do simple hello world program we need the following

index.html <- main html file

app.ts <- typescript file for module definition.

helloController.ts <- controller definition file.

tsconfig.json <- configuration file for type script.

scripts/angular.js <- angular js file from angular web site.

We will look at each one and discuss what is new with respect to TypeScript. Following is index.html

index

There is nothing new here except, I am using ‘controller as alias’.  All I am doing here is to render the message from the controller to the view through one way binding {{}}. There is not new here for type script as one would except.

If you notice closely, the script files referenced for app.js and helloController.js are java script files instead of type script files even though we will develop in type script files.

When I started out, I did have them as app.ts file instead of app.js. SO be mindful of that. When using TypeScript files (.ts extention), even though we develop using TypeScript at the end we transcompile them into javascript files so those are the files we need to reference in html files or anywhere.

Before we start adding working on controllers we need to two things

  1. First we need to bring in type script definition for angular.js so that, VSC can show intellisense. Before we do that, make sure you download angular.js file and drop it in some folder to distinguish them as framework script files. In my case, I created a script folder and dropped it in there.  With angular script file in place, open command prompt and run the following command at the root of the application directory, in our case @ “c:\users\unni\learningangularts\blog1

tsd install angular –resolve –overwrite –save

On running it should identify angular.js in the directory structure and bring in its type definition and also its dependencies. It seems angular.js still have dependency to jquery.js so it will bring the type definition of jquery as well. So you should expect to see something like the following

tsd

This should bring in the type definition for angular files and put them in typing folder.

2. Next we need to tell type script when it is transcompiling, when type of javascript should it create. In our case, we will try to create ES5 compliant javascript. It is done through creating “tsconfig.json

{
“compilerOptions”: {
“target”: “es5”
}
}

Now lets look at the type script magic.  Lets start with app.ts file.

angular.module(“helloWorld”, []);

Even though it is TypeScript file there is nothing type script about it. This is simple angular module definition as you would in normal angular app.

Next look at the hello controller;

//interface definition for model

interface IHelloWorldModel {
message: string;
}

//controller definition

class helloCtrl implements IHelloWorldModel{
message: string;

constructor(){
this.message = “Hello world!”;
}
}

//adding controller to angular module.

angular.module(“helloWorld”)
.controller(“helloCtrl”, helloCtrl);

When developing TypeScript files, it is recommended to create the interface for each controller, which need to be implemented so that view can get them. In other words, all the items in interface will be exposed in the view so by creating interface, the controller which implements forced to implement them.

In our example,  in index.html we are only displaying {{vm.message}} so we need only message in the interface. When defining the interface, make sure you specify the type also in there, which forces the controller to use the same type thus forcing strong type checking.

Next part is creating the controller itself. We use traditional class to define the controller than creating a function like you used to when created as javascript file. We make sure the controller implements the interface definition. In our case we need only message. So define it and in the constructor, pass a string to it.

At the end add the controller class to the module.It is very important, adding controller has to happen after the class definition.

One thing I forgot to mention to run the website through VSC we need a light weigh http server. Fortunately for us, there is one available through npm called http-server,  install it with npm like the following

npm install -g http-server

and then run it from the root directory of index.html file. This will start the server at specific port. once it is running without any errors,

httpserver.png

so far we have only created the TypeScript files, before we can run the code, we need to make sure we compile and generate the javascript file. Ctrl+Shift+B will build and generate the javascript file. But when you try to do this first time, vsc looks for a task file and since we did not create one, it will ask do you want to create one and acknowledge yes. It will create a task file.

Before we compile it, we need to make one quick change to that file. Open the tasks.json file under .vscode filer as shown in the picture below;

tasks

remove the HelloWorld from line 24 and make it empty as shown in the above pic. With all in place, perform compile (ctrl + shift + B), it should compile and generate the javascript files. If you look at the file structure to the left, you will see app.js next to app.ts and helloController.js next to helloController.ts.

With http-server running and all files generated, fire up a browser and go localhost:8080 should show hello world as shown below.

result

You can get the code from https://github.com/ksunair/learningangularts-blog1

I might have skipped over few things, if you have any questions, please let me know.

Happy Scripting…

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s