Angular 2 Hello World
使用的Angular 2.0 Beta版!
Angular2可算是一个十足的富二代,它爹是微软,他妈是Google,为什么说微软是爹,Google是妈呢?因为Angular2是由typescript开发的(生男生女可是由爹决定的!~)
- 安装必要的依赖包:
随便找个地方新建文件夹 angular2-helloworld,打开cmd,cd进入angular2-helloworld文件夹目录
npm init
一路回车狂飙,此时生成package.json文件(如果你还没有装node环境,那还看个毛线,赶紧先安装了再回来!!)
npm install angular2 systemjs --save
npm install -g typescript http-server
Systemjs:这货是一个AMD/ES6模块加载器;
记得将typescript http-server安装成全局的,以备待会用。然后在当前项目也装一下typescript 和 http-server
npm install typescript http-server --save-dev
(加--save安装的包会添加到package.json的dependencies下,加--save-dev安装的包会自动添加到devDependencies下,你知道啊?那我多嘴了,呵呵~)
- 开始写个hello world~
新建一个main.ts文件(记得文件后缀是.ts)
import {Component} from 'angular2/core' import {bootstrap} from 'angular2/platform/browser' @Component({ selector: 'my-app', template: '<h1>Hello {{ str }}!!!</h1>' }) export class AppComponent{ public str = 'World'; }; bootstrap(AppComponent);
再新建一个index.html文件
<!DOCTYPE html> <html> <head> <title>Angular 2 Helloworld</title> <!-- 1. Load libraries --> <script src="node_modules/angular2/bundles/angular2-polyfills.js"></script> <script src="node_modules/systemjs/dist/system.src.js"></script> <script src="node_modules/rxjs/bundles/Rx.js"></script> <script src="node_modules/angular2/bundles/angular2.dev.js"></script> <!-- 2. Configure SystemJS --> <script> System.import('main.js').then(null, console.error.bind(console)); </script> </head> <body> <!-- 3. Display the application --> <my-app>Loading...</my-app> </body> </html>
- 运行hello world程序
在cmd中输入
tsc --init
生成tsconfig.json(这货是将.ts文件编译为js文件的配置,还有其他参数,可以自行研究)tsconfig.json内容为:
{ "compilerOptions": { "target": "ES5", "module": "system", "moduleResolution": "node", "sourceMap": true, "emitDecoratorMetadata": true, "experimentalDecorators": true, "removeComments": false, "noImplicitAny": false }, "exclude": [ "node_modules" ] }
开始编译.ts为.js, 输入
tsc --watch
此时会生成main.js 和相应的 main.js.map
新打开cmd窗口 运行
http-server
在浏览器输入 127.0.0.1:8080 你会看到又大又黑的
Hello World!!!