[Step-by-Step Angular2] (1) Hello World and automation environment construction

Source: Internet
Author: User
Tags export class

With the release of RC (Release Candidate, candidate version) version of the launch, the attention of ANGULAR2 finally to the official release is not far away! The NG-CONF conference, held in early May, has been around for one months, and most APIs have been kept in a relatively stable state-and of course there are exceptions like router, which have been largely reworked in the RC phase-but, to be sure, Learning Angular2 is the right time.

Google has prepared a complete set of documentation and tutorials for ANGULAR2, which is arguably the best textbook for learning the New framework (Https://angular.io). Unfortunately, in the overview section of the basic section, the author explicitly mentions at the outset that it is a document prepared for an experienced developer (this was a practical guide to Angular for experienced Programmers who is building client applications in HTML and TypeScript). In other words, if you want to better understand the documents and tutorials on the official website, there is a certain demand for readers. Most obviously, in angular2, you need to configure the build environment and back-end support to run the entry-level Hello world--don't forget, even in the react of last year's fire, we're learning hello World can also introduce Babel through script to parse jsx at runtime (not in production, of course). If you want to count down, there are more requirements: packaging and modularity tools such as node and NPM, Webpack or SYSTEMJS, object-oriented programming, basic syntax and concepts for ES6, WEB components, and more.

Bloggers in the new technology framework is not a conservative, but a little let me worry: if the angular2 threshold is too high, then the framework for future promotion and community development will not have some negative impact? With this in mind, bloggers decided to launch a step by Step blog series, hoping to bring angular2 to more interested students who may be temporarily lacking in relevant development experience.

Here's the first of a series of blogs: Hello World and automated environment building.

The official website uses the SYSTEMJS, the Lite-server in the QuickStart, the configuration is more complex, for the sake of simplicity, this article will use everybody more familiar gulp, browserify plan. For the same purpose, the target version of the compilation will select Es6 rather than ES5, so please make sure that you have upgraded Chrome to the latest version before continuing. Also, please install the node environment first, the specific steps here will not repeat.

1. Create the project, initialize the Package.json
Create a new folder Angular2-learn, and then use the input NPM init command to initialize the NPM environment.

NPM Init

If there is no special requirement, you can always use the ENTER key until the entire process is complete. When viewing the Angular2-learn folder, you should have one more Package.json file, and one of its most important functions is to save the dependencies required for the current project.

2. Use NPM to install run dependent
Before the formal development, we need to download the relevant class library of ANGULAR2 to local, so that it can be packaged and run later. In this tutorial, we only need the following dependencies for the time being: @angular/common, @angular/compiler, @angular/core, @angular/platform-browser, @angular/ Platform-browser-dynamic
Under the Angular2-learn folder, execute the following command:

Install --save @angular/common @angular/compiler @angular/core @angular/platform-browser @angular/ Platform-browser-dynamic--registry=https://registry.npm.taobao.org

After the execution, then check the Angular2-learn directory, found a lot of node_modules folder, inside is just through the NPM install dependencies.
There are many more records under the Dependencies field in Package.json, which is the function of the--save parameter: if there are no--save parameters, the files will still be downloaded, but will not be saved to Package.json.
The--registry parameter is used to specify the image warehouse of NPM, because the network is not used by the wall,--registry many times can not complete the download Registry.npm.taobao.org is Ali to the majority of the front-end students welfare, long-term maintenance and high-speed stability, in this way also to Ali's classmates say thank you:)

3. Installing Gulp and other development dependencies
In the previous step, we downloaded the ANGULAR2 framework, which is what the ANGULAR2 framework relies on when the program runs. But we also need some other class library or framework support at compile time.
The first is gulp, we have to rely on it to complete the compilation process automation, such as detection of File modification, automatic compilation, generation of Target JS and so on.
We also need browserify because angular2 and most of the class libraries hosted in NPM follow the COMMONJS standard, not the AMD standard, and they are suitable for NODEJS environments, not browser environments. Browserify, as its name implies, can help us to "browser" code that complies with the COMMONJS standard, making it a code that complies with the AMD standard.
Of course we also need to typescript the compiler. Bloggers wanted to demonstrate the example of angular2 Hello World with a non-modular ANGULAR2 framework and native JavaScript, but after trying to find out that it might seem simpler, it was bland-a lack of support for modularity and meta-information annotations, Angular2 of the charm of a drop more than half. So here we continue to use typescript as a programming language, it is foreseeable that the ANGULAR2 team will spend most of their energy on typescript support, typescript must be the default recommended language angular2. For those unfamiliar with typescript, actually don't worry, Typescript is a superset of JavaScript, all legitimate JavaScript code is a legitimate typescript code, as long as the object-oriented foundation is relatively solid, Learning will have a same strain feeling, the curve will not be too steep.
First, install Gulp.

Install -G Gulp--registry=https://registry.npm.taobao.org

Note that we used the-G instead of the--save parameter in this step. This is because Gulp is installed in the global, not for a particular project, and G refers to global. Readers in the Linux and Mac environments should be aware of the read and write permission issues during this step.
Then go back to the Angular2-learn folder and install compile-time dependencies for the project:

Install --save-dev Gulp gulp-browserify gulp-typescript--registry=https://  Registry.npm.taobao.org

Why use--save-dev rather than--save here? Because these tools are only used when the script is compiled, the resulting JS does not have their shadow, and therefore can only be counted as development dependencies.
After the installation is complete, check the Package.json and find that several tools have been added to the Devdependencies field.
Here we have completed the installation of the class library on which the Hello World example relies.

4. Configure Gulpfile.js
As mentioned above, the purpose of our use of Gulp is to build an automated compilation environment that produces JS code that can be run in a browser. In more detail, we need to gulp detect changes in TS (the default suffix name of the typescript script) file, and once a change occurs (such as new, modified, deleted, etc.), use Gulp-typescript to compile the script from typescript to JavaScript Since ANGULAR2 itself follows the COMMONJS standard for Nodejs, we also need to use browserify to turn it into an AMD-compliant JavaScript file after compiling from typescript to JavaScript scripts. Process See:

According to this idea, we can write the following gulpfile.js, and put it in the Angular2-learn directory:

varGulp = require (' Gulp '));varTypescript = require (' Gulp-typescript '));varBrowserify = require (' gulp-browserify ')); Gulp.task (' Compile ',function() {GULP.SRC (' App/**.ts ')        //typescript compiling configuration information. Pipe (Typescript ({target:' Es6 ', module:' Commonjs ', Moduleresolution:' Node ', Sourcemap:true, Emitdecoratormetadata:true, Experimentaldecorators:true, removecomments:false, Noimplicitany:false}). On (' Error ',function() {Console.log (' Unhandled error from typescript compilation '); })        //storing typescript compiled JavaScript files in the Out directory. Pipe (Gulp.dest ('./out ')). On (' End ',function() {Console.log (' Typescript compilation Done '); //use Main.js as a portal file and merge with browserify by AMD specificationGULP.SRC (' Out/main.js '). Pipe (Browserify ()). On (' Error ',function(Error) {Console.log (' Unhandled error from browserify resolution ');                Console.log (Error); })                //Place the files after browserify in the project root directory. Pipe (Gulp.dest ('./'). On (' End ',function() {Console.log (' Browserify work done ');        }); });}); Gulp.task (' Default ', [' compile '],function() {Gulp.watch (' App/**.ts ', [' compile ']);});

Not familiar with the Gulp students do not need to be nervous, this configuration file is actually to express the compilation process. In addition, in the typescript compilation configuration section, here, in addition to the target set to ES6 and the official website is different, the rest of the configuration is used ANGULAR2 recommended configuration. Why compile to Es6 instead of ES5, because most of the features of ES6 are already supported by the new version of the browser, and our Hello world itself does not need to consider browser compatibility, direct use of es6 more convenient.

Once the Gulpfile is configured, the configuration of the ANGULAR2 build environment ends here.

5. Inlet Assembly APP.COMPONENT.TS
Next we go into the coding section of Angular2 Hello World. As a new front-end framework, ANGULAR2 absorbs many of the development achievements of the front-end community in recent years, such as the ES6-based modular development and typescript-provided decorators (decorator) that we will soon see. Although Typescript is a superset of JavaScript, its linguistic features are not fanciful, and most of the natural continuation of JavaScript's normal development, such as the future of the adorner will be a great hope to become part of the new ECMAScript standard.
Okay, back to the chase. We'll start by creating an app folder in the Angular2-learn root directory as a directory for all typescript scripts.
The App.component.ts file is then created in the app folder for the definition of the portal component.
In the definition of the component, we need to use the component adorner in the @angular/core module.
Import {Component} from ' @angular/core ';

Students with Java development experience will find that the use of adorners and annotations (annotation) are very similar to how they are used. In the component adorner, we need to define two properties, selector and template. Selector's role is to tell angular which elements to use on this component, which is itself similar to a CSS selector. The template is a component corresponding to the templates, which in this tutorial can temporarily be considered as a container for HTML code.
@Component ({
Selector: ' Hello-world ',
Template: ' })

Finally, the definition of the Appcomponent class. There is no need to add additional properties to this section for the time being, but as part of modular development, in order to expose the class to other files, we need to add the Export keyword to the class before it is defined.
Export class AppComponent {}

App.component.ts's full file content:

// Component Import {Component} from ' @angular/core ' was introduced from @angular/core; // use of component decorators @Component ({    //  selector tells angular where to initialize appcomponent this component    selector: ' Hello-world ',    //  appcomponent module template    : ' })//  define the AppComponent class and expose it to the external environment export class AppComponent {};

6. Startup script Main.ts
above, the definition of the Appcomponent class has been completed , we also need an initiator similar to the C language main function or the Java static Main method to start ANGULAR2 initialization. The
is still in the app directory, this time creating a main.ts file. The
Angular2 startup in the browser relies on the bootstrap function defined on @angular/platform-dynamic-browser. Why should bootstrap be defined in such a module instead of @angular/core, and is startup not a core function? In fact, ANGULAR2 is doing this in order to understand the core runtime logic and initialization logic of the coupling framework, which facilitates the loading and initialization of future backend and native mobile ends.
In addition, we need to introduce the appcomponent we just defined.
Main.ts full file content:

// introduction of bootstrap function from @angular/platform-browser-dynamic import {bootstrap} from ' @angular/ Platform-browser-dynamic '; // AppComponent Import {AppComponent} from './app.component ' was introduced from App.component.ts; // call the bootstrap function and use AppComponent as the parameter, the entry component bootstrap (AppComponent);

There is a small place in the code above to note that when introducing Appcomponent, the From './app.component ' cannot be written. The suffix of the/app.component.ts,.ts must be omitted. Otherwise, after the compilation of Typescript is complete, browserify cannot find the corresponding class and can only throw an exception.

7. Create index.html
Html! Finally came to the last coding step of this tutorial!
Because ANGULAR2 part of the runtime relies on us not to package through gulp, this needs to be loaded through a CDN, of course, not too troublesome classmates can download to the local.
The body needs to be placed in the Hello-world tag, and corresponds to the Hello-world defined by the selector attribute in the appcomponent.
Finally, we introduce the main.js in the Angular2-learn root directory, which is generated after the gulp compile and package ends.

Index.html's full content:

<!DOCTYPE HTML><HTML>    <Head>        <MetaCharSet= "Utf-8" />        <title>Angular2-learn</title>        <Metaname= "Viewport"content= "Width=device-width,initial-scale=1,user-scalable=no" />        <Scriptsrc= "Http://cdn.bootcss.com/reflect-metadata/0.1.3/Reflect.min.js"></Script>        <Scriptsrc= "Http://cdn.bootcss.com/angular.js/2.0.0-beta.17/Rx.umd.min.js"></Script>        <Scriptsrc= "Http://cdn.bootcss.com/zone.js/0.6.12/zone.min.js"></Script>    </Head>    <Body>        <Hello-world></Hello-world>        <Scriptsrc= "Main.js"></Script>    </Body></HTML>

8. Run the gulp and open it in the browser
After the above steps are completed, the structure under the Angular2-learn directory should:

On the command line, go back to the Angular2-learn directory, enter the following command and press ENTER:

Gulp

If the above code is not wrong, you should see
Typescript compilation Done
Browserify work done
And the Angular2-learn directory has more out folders and Main.js. When you open the local index.html in your browser, you should see the final effect.


Because gulp monitors changes to TS files, if you want to modify and debug later, just refresh the page after the browserify work-done hint.

ANGULAR2 Hello World Example and the subsequent tutorial required for the automation of the compilation environment is finished, the ANGULAR2 is not more or less a bit of a feeling? Read on to the next tutorials in this series.

[Step-by-Step Angular2] (1) Hello World and automation environment construction

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.