推荐官方学习文档
安装开发环境
新建一个文件夹simpleExample,创建一个文件名为tsconfig.json的文件,内容为:
{
"compilerOptions": {
"target": "es5",
"module": "system",
"moduleResolution": "node",
"sourceMap": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"removeComments": false,
"noImplicitAny": false
},
"exclude": [
"node_modules",
"typings/main",
"typings/main.d.ts"
]
}
创建一个文件名为typings.json的文件,内容为:
{
"globalDependencies": {
"core-js": "registry:dt/core-js#0.0.0+20160602141332",
"jasmine": "registry:dt/jasmine#2.2.0+20160621224255",
"node": "registry:dt/node#6.0.0+20160621231320"
}
}
创建一个文件名为package.json的文件,该文件中包含了我们应用所需要用到的packages,文件内容为:
{
"name": "angular2-demo",
"version": "1.0.0",
"scripts": {
"start": "concurrent \"npm run tsc:w\" \"npm run lite\" ",
"tsc": "tsc",
"tsc:w": "tsc -w",
"lite": "lite-server",
"typings": "typings",
"postinstall": "typings install"
},
"license": "ISC",
"dependencies": {
"angular2": "2.0.0-beta.7",
"systemjs": "0.19.22",
"es6-promise": "^3.0.2",
"es6-shim": "^0.33.3",
"reflect-metadata": "0.1.2",
"rxjs": "5.0.0-beta.2",
"zone.js": "0.5.15"
},
"devDependencies": {
"concurrently": "^2.0.0",
"lite-server": "^2.1.0",
"typescript": "^1.7.5",
"typings":"^0.6.8"
}
}
执行npm install 可以下载以上的依赖包
开始第一个angular 2 程序
新建文件夹名为app,在该文件目录下新建hello_world_main.ts
import {bootstrap} from "angular2/platform/browser"
import {MyHelloWorldClass} from "./hello_world_app.component"
bootstrap(MyHelloWorldClass);
同样目录下新建hello_world_app.component.ts
import {Component, View} from "angular2/core";
@Component({
selector: 'my-app'
})
@View({
template: '<h2>Hello World !!</h2>'
})
export class MyHelloWorldClass {
}
回到上一层目录新建index.html
<!DOCTYPE html>
<html>
<head>
<title>Hello World</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/es6-shim/0.33.3/es6-shim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/systemjs/0.19.20/system-polyfills.js"></script>
<script src="https://code.angularjs.org/2.0.0-beta.6/angular2-polyfills.js"></script>
<script src="https://code.angularjs.org/tools/system.js"></script>
<script src="https://code.angularjs.org/tools/typescript.js"></script>
<script src="https://code.angularjs.org/2.0.0-beta.6/Rx.js"></script>
<script src="https://code.angularjs.org/2.0.0-beta.6/angular2.dev.js"></script>
<script>
System.config({
transpiler: 'typescript',
typescriptOptions: { emitDecoratorMetadata: true },
packages: {'app': {defaultExtension: 'ts'}},
map: { 'app': 'app' }
});
System.import('app/hello_world_main')
.then(null, console.error.bind(console));
</script>
</head>
<body>
<my-app>Loading...</my-app>
</body>
</html>
index.html中使用SystemJS加载所需的模块,通过System.config函数配置。
配置详情为:
packages 告知System loader当没有文件名或者没有后缀的时候如何加载文件
map 告知System loader在何处加载所需的文件,此处app(左边)指向的是名为app(右边)的目录,所以在import的时候可以找到在app目录下的hello_world_main.ts 文件。