angular-cn/public/docs/ts/latest/guide/gettingStarted.jade

312 lines
11 KiB
Plaintext

include ../../../../_includes/_util-fns
:markdown
Let's start from zero and build a simple Angular 2 application in TypeScript.
.callout.is-helpful
header Don't want TypeScript?
:markdown
Although we're getting started in TypeScript, you can also write Angular 2 apps
in JavaScript and Dart by selecting either of those languages from the combo-box in the banner.
:markdown
We'll do it in short steps
1. Install the prerequisites for Angular TypeScript development
1. Create an application folder
1. Install the npm packages our app needs
1. Prepare for TypeScript compilation
1. Create an *index.html*
1. Write the root component for our application in *app.ts*
1. Bootstrap the app
1. Compile the TypeScript to JavaScript
1. Run it
.l-main-section
:markdown
## Prerequisites
We'll need a base of tools for all of our application development. We'll only install these once starting with
[**node** and **npm**](https://docs.npmjs.com/getting-started/installing-node "Installing Node.js and updating npm").
Now use npm in a terminal (or Windows/Linux command line) to install the **TypeScript compiler** globally
pre.prettyprint.lang-bash
code npm install -g typescript
:markdown
Use npm again to install the [**tsd package manager**](https://www.npmjs.com/package/tsd "TSD Package Manager")
so we can download TypeScript type definitions ("d.ts" files)
from the [DefinitelyTyped](http://definitelytyped.org/) repository.
pre.prettyprint.lang-bash
code npm install -g tsd
:markdown
Install a node **static server** to serve our application.
We'll use **live-server** for this example because it performs a live reload by default and it's
fun to watch the browser update as we make changes.
pre.prettyprint.lang-bash
code npm install -g live-server
.l-main-section
:markdown
## Create the application folder
Create a new folder to hold our application project, perhaps like this:
pre.prettyprint.lang-bash
code mkdir firstNgApp && cd firstNgApp
:markdown
We'll refer to this as our application's **root folder**.
.l-main-section
:markdown
## Install npm packages
Our application will need some 3rd party JavaScript files:
>***angular.js***, the Angular 2 library.
>***es6-module-loader***, a "shim" that enables today's browsers load files
using the latest "ES6" JavaScript syntax.
>***system.js***, a third-party open-source library that adds module loading functionality to our browser.
>***traceur-runtime.js*** to transpile the TypeScript-generated JavaScript into the version of Javascript
our browser understands (the version known as "ES5").
For our little "GettingStarted" app, we could just install these packages
with four npm commands.
In our real apps, we'd take an extra minute to create a *package.json* configuration file.
This is a more robust, less error-prone approach, that we can maintain as our application evolves.
Create this **package.json** file in the root folder:
```
{
"name": "getting-started",
"version": "0.0.1",
"dependencies": {
"angular2": "2.0.0-alpha.35",
"es6-module-loader": "^0.16",
"systemjs": "^0.16",
"traceur": "0.0.91"
}
}
```
Now we install our script packages with one command
pre.prettyprint.lang-bash
code npm install
.l-main-section
:markdown
## Prepare for TypeScript Compilation
We're done at the root level of our application.
We'll build the rest of the application in a subfolder called *src*.
Let's make that folder and go there.
pre.prettyprint.lang-bash
code mkdir src && cd src
:markdown
We have one last preparation step before we start coding.
We prefer writing TypeScript apps in an editor that understands TypeScript,
an editor such as [Visual Studio Code](https://code.visualstudio.com/) or
[Web Storm](https://www.jetbrains.com/webstorm/features/).
We need to tell that editor how to interpret our TypeScript
which we do with a configuration file named **tsconfig.json**.
This configuration file also simplifies the TypeScript compilation command we'll run later in this story.
Create *tsconfig.json* now with the following JSON content:
```json
{
"compilerOptions": {
"target": "ES5",
"module": "commonjs",
"sourceMap": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true
}
}
```
.l-main-section
:markdown
## Create an *index.html*
Add a new `index.html` file to the project folder and enter the following HTML
+makeExample('gettingstarted', 'ts/src/index.html', 'index.html')
.l-sub-section
:markdown
Notice in the `<head>` element that we're loading the scripts we installed earlier with npm.
There's an element called `<app>` in the `<body>`. This is a placeholder for the *root* of our
application. Angular will display our application content here.
The final inline script tells *system.js* to load another JavaScript file named "app".
We haven't written that file yet; let's do so now.
.l-main-section
:markdown
## Write the *app* component
Create an *app.ts* file and add an empty class called `AppComponent` as follows:
+makeExample('gettingstarted', 'ts/src/app-class.ts')
:markdown
We won't ask this class to do anything. It's just an empty, meaningless class until we tell
Angular about it by decorating it with some *annotations*.
We import the `component` and `view` *annotations* that we need from the Angular library at the top of the file:
+makeExample('gettingstarted', 'ts/src/app-import.ts')
:markdown
Then we apply those annotations to the `AppComponent` class by writing the following lines
just above the class definition:
+makeExample('gettingstarted', 'ts/src/app-class-w-annotations.ts')
.l-sub-section
:markdown
TypeScript recognizes the `@` symbol as a prefix for a class annotation.
The **`@Component`** annotation tells Angular this class is a component
that controls the element named "my-app".
You may remember we added such an element to our *index.html* above.
The **`@View`** annotation identifies the "view" - the HTML template -
that defines the visual appearance of this component. We're writing the HTML template inline
in this example. Later we'll move the HTML to a view template file and
assign the template's filename to the `templateUrl`.
We'll prefer that practice for all but the most trivial templates.
.l-main-section
:markdown
## Bootstrap the app
Finally, we tell Angular to start running our app
with an instance of the `AppComponent` class as the root component.
We call this "bootstrapping the app".
+makeExample('gettingstarted', 'ts/src/app-bootstrap.ts')
:markdown
Here is the complete *app.ts*
+makeExample('gettingstarted', 'ts/src/app.ts', 'app.ts')
.l-main-section
:markdown
## Compile the TypeScript to JavaScript
We've written our app in TypeScript but the browser only understands JavaScript.
We must run the TypeScript compiler to produce JavaScript for the browser.
Open a terminal window in the **root of the application folder** (not *src*) and enter:
pre.prettyprint.lang-bash
code tsc -p src -w
:markdown
After it runs we should find the generated *app.js* file in the *src* folder and also an *app.map.js* file that
helps debuggers navigate between the JavaScript and the TypeScript source.
We gave *tsc* the watch option (`-w`). It will watch for changes to our *.ts* files and
recompile them automatically. Leave it running in this terminal window.
.l-main-section
:markdown
## Run it!
Now we are ready to see this app in action.
Open a another terminal window in the **root of the application folder** (not *src*) and
launch a node static server such as the *live-server* we recommended earlier:
pre.prettyprint.lang-bash
code live-server --open src
:markdown
**live-server** loads the browser for us, serves the HTML and JavaScript files, and we should see it display our
application message:
figure.image-display
img(src='/resources/images/examples/setup-example1.png' alt="Example of Todo App")
:markdown
### Make some changes
**live-server** detects changes to our files and refreshes the browser page for us automatically.
Try changing the message to "My SECOND Angular 2 app".
The TypeScript compiler running in the first terminal window is watching our source code. It recompiles and produces
the revised *app.js*. The *live-server* sees that change and reloads the browser.
Pretty nice!
.l-main-section
:markdown
## Add Type Definition Files (optional)
Code editors (such as [Visual Studio Code](https://code.visualstudio.com/) and
[Web Storm](https://www.jetbrains.com/webstorm/features/))
improve the development experience by checking type information and
displaying API documentation ("intellisense") based on TypeScript type definition files.
We can download type definitions files for third-party libraries such as Angular
from the [DefinitelyTyped](http://definitelytyped.org/) repository using the
[**tsd package manager**](https://www.npmjs.com/package/tsd "TSD Package Manager")
that we installed earlier.
Let's download and install the core set of type definitions files for Angular development
in the ***src* folder** of our application.
pre.prettyprint.lang-bash
code tsd install angular2 es6-promise rx rx-lite --save
:markdown
We'll find a new ***typings*** folder
with subfolders for each of the downloaded type definition files (angular, es6-promise, rx, and rx-lite).
Type definition files have names ending in ***d.ts***.
There's also a summary ***tsd.d.ts*** file containing references to each of them.
Check your editor's documentation for instructions on using the *tsd.d.ts* file to
light up type checking and intellisense for these libraries.
.l-main-section
:markdown
## It's all a tree
We can think of Angular apps as a tree of components.
The `AppComponent` that we've been talking about acts as the top
level container - the root of the tree - for the rest of our application.
There's nothing special about the `AppComponent` name and we can use whatever makes sense to us.
We've pinned the root component to an element in the `index.html` file where our application will
render its view. The element is called `<my-app>` but there is nothing special about this
name either.
The *root component* loads the initial template for the application.
That template could load other components such as menu bars, views, and forms
that display information and respond to user gestures.
And these components could load yet more components until the browser page became a deep tree
of nested functionality.
We'll walk through examples of these scenarios in the following pages.