Mainly Devel Notes

Twitter, GitHub, StackOverflow: @ovrmrw (short hand of "overmorrow" that means the day after tomorrow)

Angular2 for TypeScript official tutorial - and - some additional playings

Angular2, TypeScript, System.js

(This post is English version of Angular2 for TypeScriptの公式チュートリアルを少しアレンジして遊んでみた。)

I love TypeScript and never want to develop the modern web app with other tools.
Several months ago, I heard that the Angular2 team decided to unite with TypeScript. Wow. What a great news! One of the best marriage in the 21st century!
For some reason I found the official Angular2 tutorial and tried it. Wow. One of the (...) century! But... I will forget this fantastic experience because unfortunately I have less memory to keep it on my memory.(I'm over 30)
That is why I've determined to write this down here.

(My development environment is Windows7 and Visual Studio Code)

5 MIN QUICKSTART

In this case, I'll be nearly along with above official tutorial, and add a little bit of arrangement.
For the first, make a directory somewhere you like, then

Install libraries from Npm

npm init -y
npm install angular2@2.0.0-alpha.47 --save --save-exact 
npm install systemjs jquery lodash numeral moment --save
npm install live-server typescript --save-dev

Although the official tutorial doesn't include jQuery, Lodash, Numeral, Moment, we want to use them because they are very very useful.


And of course we want to use Definitely Typed files.
Don't forget to install TSD. That's a common sense of TypeScript users:)

npm install -g tsd typescript

Initialize TSC and TSD to create tsconfig.json and tsd.json

tsc --init
tsd init

Install Definitely Typed files by using TSD.

tsd install jquery lodash numeraljs moment --save

Caution, just for TSD, you have to type "Numeraljs" instead of "Numeral". Why? I don't know.

Make directories as official tutorial structure

mkdir src
cd src
mkdir app

Good job! Installation has finished now.


Edit (root)/tsconfig.json

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

In this tutorial, "experimentalDecorators": true and "target": "es5" are needed.
If you change "module": "commonjs", it needs "moduleResolution": "node".
Others are on your favorites.


Create a file, (root)/src/index.html

<html>
<head>
  <title>Angular 2 QuickStart</title>
  <script src="../node_modules/systemjs/dist/system.js"></script>
  <script src="../node_modules/angular2/bundles/angular2.dev.js"></script>
  <script src="config.js"></script>
  <script>
    System.import('app/app');
  </script>
</head>
<body>
  <my-app>loading...</my-app>
  <script src="../node_modules/jquery/dist/jquery.min.js"></script>
  <script src="../node_modules/lodash/index.js"></script>
  <script src="../node_modules/moment/min/moment.min.js"></script>
  <script src="../node_modules/numeral/min/numeral.min.js"></script>
</body>
</html>

Some parts are different from the official tutorial, but this will work.
I wrote about`System.config() in config.js file.
That is a style of Aurelia.js which is one of the my favorite frameworks.


Create a file, (root)/src/config.js

System.config({
  baseURL: '.', // baseURL will be (root)/src/
  packages: {
    'app': { defaultExtension: 'js' }
  }
});

Due to packages property, even though the same name files are in a direcotry, System.js won't stray.

  • (root)/src/app/app.ts
  • (root)/src/app/app.js

In above case, System.import('app/app') will look up "app.js" file at runtime.


My app.ts is alike with the official tutorial's one, but I added some parts.
There are additional import sentences for Lodash, Moment, Numeral.
It is a safe way to write script tag in HTML to import libraries which create an object on window object.
For example, jquery, lodash, numeral, moment, etc.

Create a file, (root)/src/app/app.ts

import {bootstrap, Component} from 'angular2/angular2';
//import * as _ from 'lodash'; // Rejected because of error at runtime
//import * as moment from 'moment'; // Rejected because of error at runtime
//import * as numeral from 'numeral'; // Rejected because of error at runtime

@Component({
  selector: 'my-app',
  template: `
      <h1>My First Angular 2 App</h1>      
      <hr>
      <h2>{{fullName}}</h2>
      <div><input type="text" [(ng-model)]="firstName" /></div>
      <div><input type="text" [(ng-model)]="lastName" /></div>
      <hr>
      <h2>{{formattedNumeralValue}}</h2>
      <div><input type="text" [(ng-model)]="numeralValue" /></div>
      <hr>
      <h2>{{formattedMomentValue}}</h2>
      <div><input type="text" [(ng-model)]="momentValue" /></div>
    `
})
class AppComponent {
  firstName: string = 'T';
  lastName: string = 'N';
  numeralValue: number = 1000000;
  momentValue: string = '2015-11-01';
  get fullName() {
    if (!_.isEmpty(this.firstName) && !_.isEmpty(this.lastName)) {
      return `${this.firstName} ${this.lastName}`;
    } else {
      return 'Input both of name fields.';
    }
  }
  get formattedNumeralValue(){
    return numeral(this.numeralValue).format('0,0.000');
  }
  get formattedMomentValue(){
    return moment(this.momentValue).format('MMMM Do YYYY, h:mm:ss a');
  }
}
bootstrap(AppComponent);

Some explanations.
1.@Component decorator decides how to associate AppComponent class with HTML.
2.selector in @Component is linked with the same name tag in HTML, it is needed to inject template into HTML.
3.Don't forget bootstrap() for Data Binding.


Finally, the rest of you have to do is just to invoke.

Edit "scripts" part in (root)/package.json

{
  "scripts": {
    "tsc": "./node_modules/.bin/tsc -p . -w",
    "start": "live-server --open=src"
  },
}

"live-server --open=src" means that the web-server(live-server) will open "http://127.0.0.1:8080/src/", if you set as --open=. then it will open "http://127.0.0.1:8080/".


The command to compile .ts files is below.

npm run tsc

That will observe changes and re-compile repeatedly while you keep the command prompt open.


The command to invoke the web server is below.

npm start

That will open your browser and show you the page automatically, and reload by any chenges of your files automatically!


Thanks for your reading. Enjoy your Angular life!