docs(quickstart-ts/dart): updated prose and example code; consolidate for TS&Dart

closes #1396
This commit is contained in:
Patrice Chalin 2016-05-14 17:40:52 -07:00 committed by Ward Bell
parent a3400d035c
commit fedc39dd52
12 changed files with 605 additions and 599 deletions

View File

@ -4,6 +4,10 @@
//- Should be one of: 'ts', 'dart' or 'js'. Set in lang specific _util-fns file.
- var _docsFor = '';
//- Should match `_docsFor`, but in this case provides the full capitalized
//- name of the language.
- var _Lang = 'TypeScript';
//- Simple "macros" used via interpolation in text:
//- e.g., the #{_priv}el variable has an `@Input` #{_decorator}.
@ -11,8 +15,14 @@
//- preceded by the article "a". (E.g., will be "annotation" for Dart)
- var _decorator = 'decorator';
//- Articles (which toggle between 'a' and 'an'). Used for, e.g.,
//- array vs. list; decorator vs. annotation.
- var _a = 'a';
- var _an = 'an';
//- TS arrays vs. Dart lists
- var _array = 'array';
//- Deprecate now that we have the articles _a and _an
- var _an_array = 'an array';
//- Promise vs. Future, etc
@ -48,6 +58,7 @@ mixin makeExample(_filePath, region, _title, stylePatterns)
- var frag = getFrag(filePath, region);
- var defaultFormat = frag.split('\n').length > 2 ? "linenums" : "";
- var format = attributes.format || defaultFormat;
- if (attributes.format === '.') format = '';
- var avoid = !!attributes.avoid;
if (title)
@ -58,6 +69,13 @@ mixin makeExample(_filePath, region, _title, stylePatterns)
code-example(language="#{language}" format="#{format}")
!= styleString(frag, stylePatterns)
//- Like makeExample, but doesn't show line numbers and
//- title is appened with `(excerpt)` if it doesn't already
//- end with a parenthetical remark.
mixin makeExcerpt(_filePath, region, _title, stylePatterns)
- if (_title && !_title.match(/\([\w ]+\)$/)) _title = _title + ' (excerpt)';
+makeExample(_filePath, region, _title, stylePatterns)(format='.')
mixin makeTabs(filePaths, regions, tabNames, stylePatterns)
- filePaths = strSplit(filePaths);
- if (adjustExamplePath) filePaths = filePaths.map(adjustExamplePath);

View File

@ -0,0 +1,12 @@
// #docregion
// #docregion import
import 'package:angular2/core.dart';
// #enddocregion import
// #docregion metadata
@Component(
selector: 'my-app',
template: '<h1>My First Angular 2 App</h1>')
// #enddocregion metadata
// #docregion class
class AppComponent {}

View File

@ -1,10 +1,8 @@
// #docregion
import 'package:angular2/core.dart';
import 'package:angular2/platform/browser.dart';
@Component(selector: 'my-app', template: '<h1>My First Angular 2 App</h1>')
class AppComponent {}
import 'package:angular2_getting_started/app_component.dart';
main() {
void main() {
bootstrap(AppComponent);
}

View File

@ -0,0 +1,14 @@
/* #docregion */
h1 {
color: #369;
font-family: Arial, Helvetica, sans-serif;
font-size: 250%;
}
body {
margin: 2em;
}
/*
* See https://github.com/angular/angular.io/blob/master/public/docs/_examples/styles.css
* for the full set of master styles used by the documentation samples
*/

View File

@ -9,6 +9,6 @@ import { Component } from '@angular/core';
template: '<h1>My First Angular 2 App</h1>'
})
// #enddocregion metadata
// #docregion export
// #docregion class
export class AppComponent { }
// #enddocregion export
// #enddocregion class

View File

@ -1,25 +1,14 @@
/* #docregion */
/* Master Styles */
h1 {
color: #369;
font-family: Arial, Helvetica, sans-serif;
font-size: 250%;
}
h2, h3 {
color: #444;
font-family: Arial, Helvetica, sans-serif;
font-weight: lighter;
}
body {
margin: 2em;
}
body, input[text], button {
color: #888;
font-family: Cambria, Georgia;
}
/*
/*
* See https://github.com/angular/angular.io/blob/master/public/docs/_examples/styles.css
* for the full set of master styles used by the documentation samples
*/

View File

@ -39,9 +39,6 @@
packages: packages
}
// filterSystemConfig - index.html's chance to modify config before we register it.
if (global.filterSystemConfig) { global.filterSystemConfig(config); }
System.config(config);
})(this);

View File

@ -1,7 +1,6 @@
/**
* System configuration for Angular 2 samples
* Adjust as necessary for your application needs.
* Override at the last minute with global.filterSystemConfig (as plunkers do)
*/
(function(global) {
@ -42,9 +41,6 @@
packages: packages
}
// filterSystemConfig - index.html's chance to modify config before we register it.
if (global.filterSystemConfig) { global.filterSystemConfig(config); }
System.config(config);
})(this);

View File

@ -4,18 +4,21 @@ include ../../../_includes/_util-fns
- var _docsFor = 'dart';
- var _decorator = 'annotation';
- var _array = 'list';
- var _an_array = 'a list';
- var _an_array = 'a list'; //- Deprecate now that we have the articles
- var _a = 'an';
- var _an = 'a';
- var _priv = '_';
- var _Lang = 'Dart';
- var _Promise = 'Future';
- var _Observable = 'Stream';
mixin liveExampleLink(linkText, exampleUrlPartName)
a(href='https://angular-examples.github.io/#{exampleUrlPartName}')= linkText
a(href='https://angular-examples.github.io/#{exampleUrlPartName}' target="_blank")= linkText
mixin liveExampleLink2(linkText, exampleUrlPartName)
- var liveExampleSourceLinkText = attributes.srcLinkText || 'view source'
| #[+liveExampleLink(linkText, exampleUrlPartName)]
| (#[a(href='https://github.com/angular-examples/#{exampleUrlPartName}') #{liveExampleSourceLinkText}])
| (#[a(href='https://github.com/angular-examples/#{exampleUrlPartName}' target="_blank") #{liveExampleSourceLinkText}])
- var adjustExamplePath = function(_path) {
- if(!_path) return _path;
@ -25,9 +28,11 @@ mixin liveExampleLink2(linkText, exampleUrlPartName)
- // if(extn == 'dart') return path;
- var baseName = getBaseFileName(path) || path; // TODO: have getBaseFileName() return path
- var baseNameNoExt = baseName.substr(0,baseName.length - (extn.length + 1));
- var inWebFolder = baseNameNoExt.match(/^(main|index)$/);
- var inWebFolder = baseNameNoExt.match(/^(main|index(\.\d)?)$/);
- // Adjust the folder path, e.g., ts -> dart
- folder = folder.replace(/(^|\/)ts\//, '$1dart/').replace(/(^|\/)app($|\/)/, inWebFolder ? '$1web$2' : '$1lib$2');
- folder = folder.replace(/(^|\/)ts($|\/)/, '$1dart$2').replace(/(^|\/)app($|\/)/, inWebFolder ? '$1web$2' : '$1lib$2');
- // Special case not handled above: e.g., index.html -> web/index.html
- if(baseNameNoExt.match(/^(index|styles)(\.\d)?$/)) folder = (folder ? folder + '/' : '') + 'web';
- // In file name, replace special characters with underscore
- baseNameNoExt = baseNameNoExt.replace(/[\-\.]/g, '_');
- // Adjust the file extension
@ -40,7 +45,7 @@ mixin liveExampleLink2(linkText, exampleUrlPartName)
- var title = _title.trim();
- // Assume title is a path if it ends with an extension like '.foo',
- // optionally followed by some comment in parentheses.
- var matches = title.match(/(.*\.\w+)($|\s*\([\w ]+\)?$)/);
- var matches = title.match(/(.*\.\w+)($|\s*\([\w ]+\)$)/);
- if(matches && matches.length == 3) {
- // e.g. matches == ['abc.ts (excerpt)', 'abc.ts', ' (excerpt)']
- var path = adjustExamplePath(matches[1]);

View File

@ -1,136 +1,69 @@
include _util-fns
extends ../../ts/latest/quickstart.jade
:marked
Let's start from zero and build a super simple Angular 2 application in Dart.
block includes
include _util-fns
- var _Install = 'Get'
- var _prereq = 'the Dart SDK'
- var _angular_browser_uri = 'package:angular2/platform/browser.dart'
- var _angular_core_uri = 'package:angular2/core.dart'
- var _appDir = 'lib'
- var _indexHtmlDir = 'web'
.callout.is-helpful
header Don't want Dart?
block setup-tooling
:marked
Although we're getting started in Dart, you can also write Angular 2 apps
in TypeScript and JavaScript.
Just select either of those languages from the combo-box in the banner.
Install the **[Dart SDK](https://www.dartlang.org/downloads/)**,
if not already on your machine, and any tools you like to use with Dart.
The Dart SDK includes **[pub][pub]**, the Dart package manager, that we
will be using shortly.
If you don't have a favorite Dart editor already, try
[WebStorm][WS], which comes with a Dart plugin.
You can also download [Dart plugins for other IDEs and editors][DT].
p.
These instructions assume that you already have the
<a href="https://www.dartlang.org/downloads/">Dart SDK</a>
and any tools you like to use with Dart.
If you don't have a favorite editor already, try
<a href="https://confluence.jetbrains.com/display/WI/Getting+started+with+Dart">WebStorm</a>,
which comes with a Dart plugin.
You can also download
<a href="https://www.dartlang.org/tools/">Dart plugins for
other IDEs and editors</a>.
Once you have the Dart SDK and any other tools you want, return here.
[WS]: https://confluence.jetbrains.com/display/WI/Getting+started+with+Dart
[DT]: https://www.dartlang.org/tools
[pub]: https://www.dartlang.org/tools/pub
block download-source
// exclude this section from Dart
//- ##########################
.l-main-section
h2#section-install-angular Set up a new app directory
block package-and-config-files
:marked
Create a new directory,
and put a file named `pubspec.yaml` in it.
In the project folder just created, put a file named
**[pubspec.yaml][pubspec]** in it.
As shown below, in `pubspec.yaml`, specify the angular2 and browser
packages as dependencies, as well as the angular2 transformer.
Angular 2 is still changing, so provide an exact version: **2.0.0-beta.17**.
code-example(language="sh").
&gt; <span class="blk">mkdir angular2_getting_started</span>
&gt; <span class="blk">cd angular2_getting_started</span>
&gt; <span class="blk">vim pubspec.yaml</span> # Use your favorite editor!
p.
In <code>pubspec.yaml</code>,
specify the angular2 and browser packages as dependencies,
as well as the angular2 transformer.
Angular 2 is still changing, so provide an exact version:
<b>2.0.0-beta.17</b>.
[pubspec]: https://www.dartlang.org/tools/pub/pubspec.html
+makeExample('quickstart/dart/pubspec.yaml', 'no-rewriter', 'pubspec.yaml')
p.
In the same directory, create a <code>web</code> directory, and then
run <code>pub get</code> to install the angular2 and browser packages
(along with the packages they depend on).
block install-packages
:marked
From the project folder, run `pub get` to install the angular2 and browser
packages (along with the packages they depend on).
code-example(language="sh").
&gt; <span class="blk">mkdir web</span>
&gt; <span class="blk">pub get</span>
Resolving dependencies...
//- PENDING: Create template? Link to pub/pubspec docs?
//- ##########################
.l-main-section
h2#section-transpile Create a Dart file
p.
Create a file under <code>web</code> named <code>main.dart</code>.
code-example(language="sh").
&gt; <span class="blk">vim web/main.dart</span> # Use your favorite editor!
p.
Paste the following code into <code>web/main.dart</code>:
+makeExample('quickstart/dart/web/main.dart', null, 'web/main.dart')
block annotation-fields
:marked
You've just defined an Angular 2 **component**,
one of the most important Angular 2 features.
Components are the primary way to create application views
and support them with application logic.
This component is an empty, do-nothing class named `AppComponent`.
You can add properties and application logic to it later,
when you're ready to build a substantive application.
Above the class is the `@Component` annotation,
which tells Angular that this class *is an Angular component*.
The call to the `@Component` constructor has two
named parameters, `selector` and `template`.
The `selector` parameter specifies a CSS selector for
a host HTML element named `my-app`.
Angular creates and displays an instance of `AppComponent`
wherever it encounters a `my-app` element.
The `template` parameter is the component's companion template
that tells Angular how to render a view.
In this case, the template is a single line of HTML announcing
"My First Angular 2 App".
The <code>main()</code> function
calls Angular's <code>bootstrap()</code> function,
which tells Angular to start the application with `AppComponent`
at the application root.
Someday the application will
consist of more components arising in tree-like fashion from this root.
The top lines import two libraries.
*All* Dart files that use Angular APIs import `core.dart`.
Only files that call `bootstrap()` import `platform/browser.dart`.
//- ##########################
.l-main-section
h2#section-angular-create-account Create an HTML file
block create-main
p.
Create a file named <code>web/index.html</code> that contains
the following code:
Now we need something to tell Angular to load the root component.
Create:
ul
li a #[b folder named #[code web]], and inside it
li the file #[code #[+adjExPath('app/main.ts')]] with the following content:
+makeExample('quickstart/dart/web/index.html', null, 'web/index.html')
:marked
The `<my-app>` tag in the `<body>` is
the custom HTML element defined in the Dart file.
//- ##########################
.l-main-section
h2#section-angular-run-app Run the app
block index-html-commentary-for-ts
//- N/A
block run-app
p.
You have a few options for running your app.
One is to launch a local HTTP server
@ -138,35 +71,35 @@ p.
<a href="https://www.dartlang.org/tools/dartium/">Dartium</a>.
You can use whatever server you like, such as WebStorm's server
or Python's SimpleHTTPServer.
p.
Another option is to build and serve the app using <code>pub serve</code>,
and then run it by visiting <b>http://localhost:8080</b> in any modern browser.
Pub serve generates the JavaScript on the fly,
and then run it by visiting <b><code>http://localhost:8080</code></b> in any modern browser.
Pub serve generates JavaScript on the fly,
which can take a while when you first visit the page.
Pub serve also runs in <b><i>watch mode</i></b>, and will re-compile and subsequently serve
and changed assets.
p.
Once the app is running,
you should see <b>My First Angular 2 App</b> in your browser window.
Once the app is running, you should see the following in your browser
window:
block build-app
.alert.is-important
:marked
If you don't see that, make sure you've entered all the code correctly
If you don't see that, make sure you've entered all the code correctly,
in the [proper folders](#wrap-up),
and run `pub get`.
//- ##########################
.l-main-section
h2#section-angular-run-app Generate JavaScript
.l-verbose-section
h3#section-angular-run-app Building the app (generating JavaScript)
:marked
Before you can deploy your app, you need to generate JavaScript files.
Pub build makes that easy.
The `pub build` command makes that easy.
To improve your app's performance, convert the
HTML file to directly include the generated JavaScript;
one way to do that is with dart_to_js_script_rewriter.
one way to do that is with `dart_to_js_script_rewriter`.
:marked
Add the dart_to_js_script_rewriter package to your pubspec,
Add the `dart_to_js_script_rewriter` package to your pubspec,
in both the `dependencies` and `transformers` sections.
- var stylePattern = { pnk: /(dart_to_js_script_rewriter.*$)|(- dart_to_js_script_rewriter.*$)/gm, otl: /(dependencies:)|(transformers:)/g };
@ -176,14 +109,13 @@ p.
Then compile your Dart code to JavaScript,
using <code>pub build</code>.
code-example(language="basic").
code-example(language="sh").
&gt; <span class="blk">pub build</span>
Loading source assets...
p.
The generated JavaScript appears, along with supporting files,
under the <code>build</code> directory.
p.
When you generate JavaScript for an Angular app,
be sure to use the Angular transformer.
@ -204,10 +136,8 @@ p.
<a href="https://github.com/angular/angular/wiki/Angular-2-Dart-Transformer">Angular
transformer wiki page</a>.
#performance.l-sub-section
h3 Performance, the transformer, and Angular 2 libraries
p.
When you import <code>bootstrap.dart</code>,
you also get <code>dart:mirrors</code>,
@ -218,22 +148,43 @@ p.
(<code>entry_points</code> in <code>pubspec.yaml</code>)
so that they don't use mirrors.
block server-watching
:marked
Pub serve is watching and
should detect the change, recompile the Dart into JavaScript,
refresh the browser, and display the revised message.
It's a nifty way to develop an application!
//- WHAT'S NEXT... ##########################
.l-main-section
h2#section-transpile Great job! Next step...
Ensure that you terminate the `pub serve` process once you are done.
<!--TODO: Join us on the [Tour of Heroes](./toh-pt1.html) -->
block project-file-structure
.filetree
.file angular2-quickstart
.children
.file build ...
.file lib
.children
.file app_component.dart
.file pubspec.yaml
.file web
.children
.file index.html
.file main.ts
.file styles.css
p.
Follow the <a href="guide">developer guide</a>
to continue playing with Angular 2 for Dart.
block project-files
+makeTabs(`
quickstart/ts/app/app.component.ts,
quickstart/ts/app/main.ts,
quickstart/ts/index.html,
quickstart/dart/pubspec.yaml,
quickstart/ts/styles.1.css`
,null,
`app/app.component.ts,
app/main.ts,
index.html,
pubspec.yaml,
styles.css`)
p.
Or read more about Angular or Dart:
ul
li
<a href="resources.html">Angular resources</a>
li
<a href="https://www.dartlang.org">dartlang.org</a>
block what-next-ts-overhead
//- N/A

View File

@ -5,7 +5,7 @@ include ../../../_includes/_util-fns
//- Other values match the defaults.
mixin liveExampleLink(linkText, exampleUrlPartName)
a(href='/resources/live-examples/#{exampleUrlPartName}/ts/plnkr.html')= linkText
a(href='/resources/live-examples/#{exampleUrlPartName}/ts/plnkr.html' target="_blank")= linkText
mixin liveExampleLink2(linkText, exampleUrlPartName)
//- In Dart this also gives a link to the source.

View File

@ -1,39 +1,65 @@
include _util-fns
block includes
include _util-fns
- var _Install = 'Install'
- var _prereq = 'Node.js'
- var _angular_browser_uri = '@angular/platform-browser-dynamic'
- var _angular_core_uri = '@angular/core'
- var _appDir = 'app'
- var _indexHtmlDir = 'project root'
:marked
Our QuickStart goal is to build and run a super-simple Angular 2 application in TypeScript.
Our QuickStart goal is to build and run a super-simple
Angular 2 application in #{_Lang}, and
establish a development environment for the remaining documentation samples
that also can be the foundation for real world applications.
# Download the code
In a hurry?
[Download the QuickStart source](https://github.com/angular/quickstart/blob/master/README.md)
and start coding.
.callout.is-helpful
header Don't want #{_Lang}?
p.
Although we're getting started in #{_Lang}, you can also write Angular 2 apps
in #{_docsFor == 'ts' ? 'Dart' : 'TypeScript'} and JavaScript.
Just select either of those languages from the combo-box in the banner.
# See it run
Try this <a href="/resources/live-examples/quickstart/ts/plnkr.html" target="_blank">live example</a>
which loads the sample app in <a href="http://plnkr.co/" title="Plunker" target="_blank">plunker</a>
and displays a simple message:
h1 Try it!
p
| Try the #[+liveExampleLink2('live example', 'quickstart')] which loads the sample app
+ifDocsFor('ts')
| &nbsp;in #[a(href="http://plnkr.co/" title="Plunker" target="_blank") plunker]
| &nbsp;and displays the simple message:
figure.image-display
img(src='/resources/images/devguide/quickstart/my-first-app.png' alt="Output of QuickStart app")
h1 Build this app!
:marked
# Learn
Of course we don't build apps to run in plunker.
The following steps establish a development environment for the documentation samples
that also can be the foundation for our real world applications. At a high level, we will
- [Prerequisite](#prereq): install #{_prereq}
- [Step 1](#create-and-configure): create the apps project folder and
define package dependencies and special project setup
- [Step 2](#root-component): create the apps Angular root component
- [Step 3](#main): add `main.#{_docsFor}`, identifying the root component to Angular
- [Step 4](#index): add `index.html`, the web page that hosts the application
- [Step 5](#build-and-run): build and run the app
- [Make some changes to the app](#make-some-changes)
- [Wrap up](#wrap-up)
- set up the [development environment](#devenv)
- write the app's Angular [root component](#component)
- write [main.ts](#main) which tells Angular to display the root component
- write the [host web page](#index) (`index.html`)
.l-main-section
h2#prereq Prerequisite: #{_prereq}
.l-sub-section
block setup-tooling
:marked
We'll see many code blocks as we pursue this agenda. They're all easy to copy and paste:
code-example(format='.', language='html').
Click the glyph on the right to copy code snippets to the clipboard ⇨⇨⇨⇨⇨⇨⇨⇨⇨⇨
Install **[Node.js® and npm](https://nodejs.org/en/download/)**
if they are not already on your machine.
block download-source
.l-main-section
.callout.is-helpful
header Download the source
:marked
Instead of following each step of these instructions, we can
[download the QuickStart source](https://github.com/angular/quickstart/blob/master/README.md)
from github and follow its brief instructions.
.l-main-section
button(class="verbose off md-primary md-button md-ink-ripple", type="button", onclick="verbose(false)").
Hide explanations
button(class="verbose on md-primary md-button md-ink-ripple", type="button", onclick="verbose(true)").
@ -46,101 +72,73 @@ button(class="verbose on md-primary md-button md-ink-ripple", type="button", onc
Click *Hide Explanations* to show only the instructions.
Click it again to see everything again.
a(id="devenv")
.l-sub-section
:marked
We'll see many code blocks as we build the QuickStart app. They're all easy to copy and paste:
code-example(format="nocode").
Click the glyph on the right to copy code snippets to the clipboard ==>
.l-main-section
:marked
## Development Environment
h2#create-and-configure Step 1: create and configure the project
We need to set up our development environment:
* install node and npm
* create an [application project folder](#app-folder)
* add a [tsconfig.json](#tsconfig) to guide the TypeScript compiler
* add a [typings.json](#typings) that identifies missing TypeScript definition files
* add a [package.json](#package-json) that defines the packages and scripts we need
* add a [systemjs.config.js](#systemjs) that configures system.js
* install the npm packages and typings files
- var _package_and_config_files = _docsFor == 'dart' ? 'pubspec.yaml' : 'package definition and configuration files'
a(id="install-npm")
:marked
**Install [node and npm](https://nodejs.org/en/download/)** if not already on your machine.
In this step we:
* [(a) Create the project folder](#create-the-project-folder).
* [(b) Add #{_package_and_config_files}](#add-config-files).
* [(c) #{_Install} packages](#install-packages).
a(id="app-folder")
:marked
Create a **new project folder**
code-example(format="").
h3 (a) Create the project folder
code-example(language="sh").
mkdir angular2-quickstart
cd angular2-quickstart
a(id="tsconfig")
:marked
Add a **tsconfig.json** file to the project folder and copy/paste the following:
+makeJson('quickstart/ts/tsconfig.1.json', null, 'tsconfig.json')(format=".")
h3#add-config-files (b) Add #{_package_and_config_files}
block package-and-config-files
- var _tsconfigUri = 'guide/typescript-configuration.html#tsconfig'
- var _typingsUri = 'guide/typescript-configuration.html#!#typings'
:marked
This `tsconfig.json` file guides the TypeScript compiler.
Learn more about it in the
<a href="guide/typescript-configuration.html#tsconfig" target="_blank">TypeScript Configuration</a> chapter.
p Add the following package definition and configuration files to the project folder:
ul
li.
#[b package.json] lists packages the QuickStart app depends on and
defines some useful scripts.
See #[a(href="guide/npm-packages.html") Npm Package Configuration] for details.
li.
#[b tsconfig.json] is the TypeScript compiler configuration file.
See #[a(href="#{_tsconfigUri}") TypeScript Configuration] for details.
li.
#[b typings.json] identifies TypeScript definition files.
See #[a(href="#{_typingsUri}") TypeScript Configuration] for details.
li.
#[b systemjs.config.js], the SystemJS configuration file.
See discussion #[a(href="#systemjs") below].
a(id="typings")
:marked
Add a **typings.json** file to the project folder and copy/paste the following:
+makeJson('quickstart/ts/typings.1.json', null, 'typings.json')(format=".")
a#config-files
+makeTabs(`
quickstart/ts/package.1.json,
quickstart/ts/tsconfig.1.json,
quickstart/ts/typings.1.json,
quickstart/ts/systemjs.config.1.js
`, '', `
package.json,
tsconfig.json,
typings.json,
systemjs.config.js
`)
.l-verbose-section
h3#install-packages (c) #{_Install} packages
block install-packages
:marked
Many JavaScript libraries extend the JavaScript environment with features and syntax
that the TypeScript compiler doesn't recognize natively. We teach it about these capabilities with
<a href="http://www.typescriptlang.org/docs/handbook/writing-declaration-files.html" target="_blank">TypeScript type definition files</a>
&mdash; *d.ts files* &mdash; which we identify in a `typings.json` file.
We install the packages listed in `package.json` using `npm`. Enter the
following command in a terminal window (command window in Windows):
We go a little deeper into *typings* in the
<a href="guide/typescript-configuration.html#typings" target="_blank">TypeScript Configuration</a> chapter.
a(id="package-json")
:marked
Add a **package.json** file to the project folder and copy/paste the following:
+makeJson('quickstart/ts/package.1.json', null, 'package.json')(format=".")
.l-verbose-section
:marked
### Adding the libraries we need with *npm*
Angular application developers rely on the <a href="https://docs.npmjs.com/" target="_blank"><i>npm</i></a>
package manager to install the libraries their apps require.
The Angular team recommends the starter-set of packages specified in the `dependencies` and `devDependencies`
sections.
See the [npm packages](guide/npm-packages.html) chapter for details.
### Helpful scripts
We've included a number of npm scripts in our suggested `package.json` to handle common development tasks:
+makeJson('quickstart/ts/package.1.json',{ paths: 'scripts'}, 'package.json (scripts)')(format=".")
:marked
We execute most npm scripts in the following way: `npm run` + *script-name*.
Some commands (such as `start`) don't require the `run` keyword.
Here's what these scripts do:
* `npm start` - runs the compiler and a server at the same time, both in "watch mode"
* `npm run tsc` - runs the TypeScript compiler once
* `npm run tsc:w` - runs the TypeScript compiler in watch mode;
the process keeps running, awaiting changes to TypeScript files and re-compiling when it sees them
* `npm run lite` - runs the <a href="https://www.npmjs.com/package/lite-server" target="_blank">lite-server</a>,
a light-weight, static file server with excellent support for Angular apps that use routing
* `npm run typings` - runs the [*typings* tool](#typings) separately
* `npm run postinstall` - called by *npm* automatically *after* it successfully completes package installation.
This script installs the [TypeScript definition files](#typings) defined in `typings.json`
:marked
**Install these packages** by entering the following *npm* command in a terminal window (command window in Windows):
code-example(format="").
code-example(language="sh").
npm install
.alert.is-important
.alert.is-important
:marked
Scary <span style="color:red; font-weight: bold">error messages in red</span> may appear **during** install.
The install typically recovers from these errors and finishes successfully.
@ -158,76 +156,110 @@ code-example(format="").
Just make sure there are no `npm ERR!` messages at the end of `npm install`.
.l-verbose-section
:marked
#### Adding the libraries and packages we need with *npm*
Angular application developers rely on the _[npm](https://docs.npmjs.com)_
package manager to install the libraries and packages their apps require.
The Angular team recommends the starter-set of packages specified in the
`dependencies` and `devDependencies` sections.
See the [npm packages](guide/npm-packages.html) chapter for details.
#### Helpful scripts
We've included a number of npm scripts in our suggested `package.json` to handle common development tasks:
+makeJson('quickstart/ts/package.1.json',{ paths: 'scripts'}, 'package.json (scripts)')(format=".")
:marked
We execute most npm scripts in the following way: `npm run` followed by a *script-name*.
Some commands (such as `start`) don't require the `run` keyword.
Here's what these scripts do:
* `npm start` - runs the compiler and a server at the same time, both in "watch mode"
* `npm run tsc` - runs the TypeScript compiler once
* `npm run tsc:w` - runs the TypeScript compiler in watch mode;
the process keeps running, awaiting changes to TypeScript files and re-compiling when it sees them
* `npm run lite` - runs the <a href="https://www.npmjs.com/package/lite-server" target="_blank">lite-server</a>,
a light-weight, static file server with excellent support for Angular apps that use routing
* `npm run typings` - runs the [*typings* tool](#{_typingsUri}) separately
* `npm run postinstall` - called by *npm* automatically *after* it successfully completes package installation.
This script installs the [TypeScript definition files](#{_typingsUri}) defined in `typings.json`
:marked
**We're all set.** Let's write some code.
a(id="component")
.l-main-section
h2#root-component Step 2: our first angular component
:marked
## Our First Angular Component
Let's create a folder to hold our application and add a super-simple Angular component.
**Create an *app* sub-folder** off the root directory and make it the current directory
code-example(format="").
mkdir app
cd app
**Create an *#{_appDir}* sub-folder** off the project root directory:
a(id="app-component")
:marked
**Add a component file** named *app.component.ts* and paste the following lines:
+makeExample('quickstart/ts/app/app.component.ts', null, 'app/app.component.ts')(format=".")
code-example.
mkdir #{_appDir}
a#app-component
p.
#[b Create the component file]
#[code #[+adjExPath('app/app.component.ts')]] (in this newly created directory) with the following content:
+makeExample('quickstart/ts/app/app.component.ts', '', 'app/app.component.ts')(format='.')
.l-verbose-section
:marked
### AppComponent is the root of the application
Every Angular app has at least one root component, conventionally named `AppComponent`,
Every Angular app has at least one **root component**, conventionally named `AppComponent`,
that hosts the client user experience.
Components are the basic building blocks of Angular applications.
A component controls a portion of the screen &mdash; a *view* &mdash; through its associated template.
This QuickStart has only one, extremely simple component.
But it has the essential structure of every component we'll ever write:
* One or more <a href="javascript: why('component-import')">import</a>
* One or more [import](#component-import)
statements to reference the things we need.
* A <a href="javascript: why('decorator')">@Component decorator</a>
* A [@Component #{_decorator}](#component-decorator)
that tells Angular what template to use and how to create the component.
* A <a href="javascript: why('class')">component class</a>
* A [component class](#component-class)
that controls the appearance and behavior of a view through its template.
a(id="component-import")
a#component-import
:marked
### Import
Angular apps are modular. They consist of many files each dedicated to a purpose.
Angular itself is modular. It is a collection of library modules
each made up of several, related features that we'll use to build our application.
When we need something from a module, we import it.
Here we import the Angular `Component` decorator function from
`@angular/core` because we need it to define our component.
+makeExample('quickstart/ts/app/app.component.ts', 'import', 'app/app.component.ts (import)')(format=".")
When we need something from a module or library, we import it.
Here we import the Angular 2 core so that our component code can have access to
the `@Component` #{_decorator}.
a(id="component-decorator")
+makeExcerpt('quickstart/ts/app/app.component.ts', 'import', 'app/app.component.ts (import)')
h3#component-decorator @Component #{_decorator}
+ifDocsFor('ts')
:marked
### @Component decorator
`Component` is a *decorator function* that takes a *metadata object* as argument.
We apply this function to the component class by prefixing the function with the
**@** symbol and invoking it with a metadata object, just above the class.
:marked
`@Component` is #{_a} **#{_decorator}** that allows us to associate *metadata* with the
component class.
The metadata tells Angular how to create and use this component.
`Component` is a **decorator** function that takes a *metadata* object.
The metadata tell Angular how to create and use this component.
+makeExcerpt('quickstart/ts/app/app.component.ts', 'metadata', 'app/app.component.ts (metadata)')(format='.')
We apply this function to the component class
by prefixing the function with the **@** symbol and invoking it with the metadata object
just above the class:
+makeExample('quickstart/ts/app/app.component.ts', 'metadata', 'app/app.component.ts (metadata)')(format=".")
block annotation-fields
:marked
This particular metadata object has two fields, a `selector` and a `template`.
:marked
The **selector** specifies a simple CSS selector for an HTML element that represents the component.
>The element for this component is named `my-app`.
@ -244,27 +276,28 @@ a(id="app-component")
These templates might identify yet other components.
In this way an Angular application becomes a tree of components.
a(id="component-class")
:marked
### Component class
At the bottom of the file is an empty, do-nothing class named `AppComponent`.
+makeExample('quickstart/ts/app/app.component.ts', 'export', 'app/app.component.ts (class)')(format=".")
+makeExcerpt('quickstart/ts/app/app.component.ts', 'class', 'app/app.component.ts (class)')
:marked
When we're ready to build a substantive application,
we can expand this class with properties and application logic.
Our `AppComponent` class is empty because we don't need it to do anything in this QuickStart.
+ifDocsFor('ts')
:marked
We **export** `AppComponent` so that we can **import** it elsewhere in our application,
as we'll see when we create `main.ts`.
a(id="main")
.l-main-section
:marked
## Show it with *main.ts*
Now we need something to tell Angular to load the root component
h2#main Step 3: add #[code #[+adjExPath('main.ts')]]
Add a new file , `main.ts`, to the `app/` folder as follows:
+makeExample('quickstart/ts/app/main.ts', null, 'app/main.ts')(format=".")
block create-main
p.
Now we need something to tell Angular to load the root component.
Create the file #[code #[+adjExPath('app/main.ts')]] with the following content:
+makeExample('quickstart/ts/app/main.ts', '', 'app/main.ts')(format='.')
.l-verbose-section
:marked
@ -276,9 +309,8 @@ a(id="main")
Then we call `bootstrap` with `AppComponent`.
### Bootstrapping is platform-specific
Notice that we import the `bootstrap` function from `@angular/platform-browser-dynamic`,
not `@angular/core`.
Notice that we import the `bootstrap` function from `#{_angular_browser_uri}`,
not `#{_angular_core_uri}`.
Bootstrapping isn't core because there isn't a single way to bootstrap the app.
True, most applications that run in a browser call the bootstrap function from
this library.
@ -288,13 +320,13 @@ a(id="main")
We might wish to render the first page of our application on the server
to improve launch performance or facilitate
[SEO](http://www.google.com/webmasters/docs/search-engine-optimization-starter-guide.pdf).
These targets require a different kind of bootstrap function that we'd import from a different library.
### Why create a separate ***main.ts*** file?
### Why create separate *main.#{_docsFor}* and app component files?
The *main.ts* file is tiny. This is just a QuickStart.
We could have folded its few lines into the `app.component` file
Both `main.#{_docsFor}` and the app component files are tiny.
This is just a QuickStart.
We could have merged these two files into one
and spared ourselves some complexity.
We'd rather demonstrate the proper way to structure an Angular application.
@ -304,62 +336,45 @@ a(id="main")
Testing the component is much easier if it doesn't also try to run the entire application.
Let's make the small extra effort to do it *the right way*.
a(id="index")
.l-main-section
h2#index Step 4: add #[code index.html]
:marked
## Add the `index.html`
The `index.html` is the web page that hosts the application
The `index.html` is the web page that hosts the application.
In the **#{_indexHtmlDir}** folder
create an`index.html` file and paste the following lines:
Navigate to the **project root folder**.
+makeExample('quickstart/ts/index.html', '', 'index.html')(format='.')
code-example(format="").
cd ..
:marked
Create an`index.html` file in this root folder and paste the following lines:
+makeExample('quickstart/ts/index.html', null, 'index.html')(format=".")
.l-verbose-section
block index-html-commentary-for-ts
:marked
There are four noteworthy sections of HTML
The noteworthy sections of HTML are:
1. The JavaScript [libraries](#libraries)
2. Configuration file for [SystemJS](#systemjs), and a script
where we import and run the `app` module which refers to the `main` file that we just wrote.
3. The [`<my-app>`](#my-app) tag in the `<body>` which is *where our app lives!*
2. Configuration file for [SystemJS](#systemjs).
3. Where we import and run the `main` file that we just wrote.
4. The [&lt;my-app>](#my-app) tag in the `<body>` which is *where our app lives!*
a(id="libraries")
:marked
### Libraries
We loaded the following scripts
+makeExample('quickstart/ts/index.html', 'libraries', 'index.html')(format=".")
+makeExcerpt('quickstart/ts/index.html', 'libraries', 'index.html')
:marked
We began with es6-shim which monkey patches the global context (window) with essential features of ES2015 (ES6).
We begin with es6-shim which monkey patches the global context (window) with essential features of ES2015 (ES6).
Next are the polyfills for Angular2, `zone.js` and `reflect-metadata`.
Then the [SystemJS](#systemjs) library for module loading.
:marked
We'll make different choices as we gain experience and
become more concerned about production qualities such as
load times and memory footprint.
a(id="systemjs")
.l-main-section
:marked
### SystemJS Configuration
The QuickStart uses <a href="https://github.com/systemjs/systemjs" target="_blank">SystemJS</a>
to load application and library modules.
Add this `systemjs.config.js` file to the project root.
+makeExample('quickstart/ts/systemjs.config.1.js', null, 'systemjs.config.js')(format=".")
.l-verbose-section
h3#systemjs SystemJS
:marked
QuickStart uses <a href="https://github.com/systemjs/systemjs" target="_blank">SystemJS</a>
to load application and library modules. [Earlier](#add-config-files) we
added the `systemjs.config.js` file to the project root.
There are alternatives that work just fine including the well-regarded
<a href="https://webpack.github.io/" target="_blank">webpack</a>.
[webpack](guide/webpack.html).
SystemJS happens to be a good choice.
But we want to be clear that it was a *choice* and not a *preference*.
@ -371,8 +386,8 @@ a(id="systemjs")
Learn more about SystemJS configuration
<a href="https://github.com/systemjs/systemjs/blob/master/docs/config-api.md" target="_blank">here</a>.
With those cautions in mind, what are we doing in this QuickStart configuration?
With those cautions in mind, what are we doing in the
QuickStart [`systemjs.config.js` configuration file we added earlier](#config-files)?
First, we create a map to tell SystemJS where to look when we import some module.
Then, we register all our packages to SystemJS:
all the project dependencies and our application package, `app`.
@ -390,21 +405,23 @@ a(id="systemjs")
Our QuickStart makes such requests when one of its
application TypeScript files has an import statement like this:
+makeExample('quickstart/ts/app/main.ts', 'app-component', 'main.ts (excerpt)')(format=".")
+makeExcerpt('quickstart/ts/app/main.ts', 'app-component', 'main.ts (excerpt)')
:marked
Notice that the module name (after `from`) does not mention a filename extension.
In the configuration we tell SystemJS to default the extension to 'js', a JavaScript file.
In the configuration we tell SystemJS to default the extension to `js`, a JavaScript file.
That makes sense because we transpile TypeScript to JavaScript
<i>before</i> running the application</a>.
*before* running the application.
.l-sub-section
:marked
#### Transpiling in the browser
In the live example on plunker we transpile (AKA compile) to JavaScript in the browser
on the fly. That's fine for a demo. That's not our preference for development or production.
on the fly. _That's fine for a demo_.
We recommend transpiling (AKA compiling) to JavaScript during a build phase
**Do not transpile in the browser during development or for production**.
We strongly recommend transpiling (AKA compiling) to JavaScript during a build phase
before running the application for several reasons including:
* We see compiler warnings and errors that are hidden from us in the browser.
@ -421,7 +438,7 @@ a(id="systemjs")
:marked
The `System.import` call tells SystemJS to import the `main` file
(`main.js` ... after transpiling `main.ts`, remember?).
(`main.js` ... after transpiling `main.ts`, remember?);
`main` is where we tell Angular to launch the application.
We also catch and log launch errors to the console.
@ -431,27 +448,28 @@ a(id="systemjs")
a(id="my-app")
:marked
### *&lt;my-app&gt;*
When Angular calls the `bootstrap` function in `main.ts`, it reads the `AppComponent`
When Angular calls the `bootstrap` function in `main.#{_docsFor}`, it reads the `AppComponent`
metadata, finds the `my-app` selector, locates an element tag named `my-app`,
and loads our application between those tags.
and renders our application's view between those tags.
.l-main-section
:marked
## Add some style
### Add some style
Styles aren't essential but they're nice and the `index.html` assumes we have
a stylesheet called `styles.css`.
Create a `styles.css` in the root folder and start styling, perhaps with this set:
+makeExample('quickstart/ts/styles.1.css', null, 'styles.css (excerpt)')(format=".")
Create a `styles.css` in the #{_indexHtmlDir} folder and start styling, perhaps with minimal
styles shown below. For the full set of master styles used by the documentation samples
see this master [styles.css](https://github.com/angular/angular.io/blob/master/public/docs/_examples/styles.css).
+makeExcerpt('quickstart/ts/styles.1.css', '', 'styles.css')
.l-main-section
:marked
## Compile and run!
h2#build-and-run Step 5: build and run the app!
block run-app
:marked
Open a terminal window and enter this command:
code-example(format="").
code-example.
npm start
:marked
:marked
That command runs two parallel node processes
1. The TypeScript compiler in watch mode
1. A static server called **lite-server** that loads `index.html` in a browser
@ -463,25 +481,32 @@ figure.image-display
img(src='/resources/images/devguide/quickstart/my-first-app.png' alt="Output of quickstart app")
:marked
Congratulations! We are in business.
**Great job!**
### Make some changes
block build-app
//- Nothing for ts.
:marked
## Make some changes
Try changing the message to "My SECOND Angular 2 app".
block server-watching
:marked
The TypeScript compiler and `lite-server` are watching.
They should detect the change, recompile the TypeScript into JavaScript,
refresh the browser, and display the revised message.
It's a nifty way to develop an application!
We close the terminal window when we're done to terminate both the compiler and the server.
.l-main-section
:marked
## Final structure
# Wrap up
## Final project structure and files
Our final project folder structure looks like this:
.filetree
block project-file-structure
.filetree
.file angular2-quickstart
.children
.file app
@ -499,7 +524,8 @@ figure.image-display
:marked
And here are the files:
+makeTabs(`
block project-files
+makeTabs(`
quickstart/ts/app/app.component.ts,
quickstart/ts/app/main.ts,
quickstart/ts/index.html,
@ -517,23 +543,23 @@ figure.image-display
typings.json,
styles.css,
systemjs.config.js`)
:marked
.l-main-section
:marked
## Wrap Up
## What next?
Our first application doesn't do much. It's basically "Hello, World" for Angular 2.
We kept it simple in our first pass: we wrote a little Angular component,
we added some JavaScript libraries to `index.html`, and launched with a
created a simple `index.html`, and launched with a
static file server. That's about all we'd expect to do for a "Hello, World" app.
**We have greater ambitions.**
**We have greater ambitions!**
block what-next-ts-overhead
:marked
The good news is that the overhead of setup is (mostly) behind us.
We'll probably only touch the `package.json` to update libraries.
We'll likely open `index.html` only if we need to add a library or some css stylesheets.
:marked
We're about to take the next step and build a small application that
demonstrates the great things we can build with Angular 2.