AngularJS 2.0 是一場徹底的重新設計,它基於 TypeScript 開發,模塊系統與裝飾器語法都和 1.x 差異極大。本文整理官方 quickstart 的環境建置流程,適合第一次接觸 2.0 的開發者。
前置需求:機器上需有 Node.js 環境。2.0 以 TypeScript 撰寫,因此還需要 tsc 編譯器與 typings 型別定義工具。
mkdir angular2-quickstart cd angular2-quickstart
{
"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"
]
}
幾個關鍵選項說明:
experimentalDecorators 與 emitDecoratorMetadata:Angular 的 @Component、@Injectable 裝飾器必須開啟這兩項module: system:輸出 SystemJS 模塊格式,搭配瀏覽器端載入器使用sourceMap:產生 .map 檔,方便除錯時對回 TypeScript 原始碼{
"ambientDependencies": {
"es6-shim": "github:DefinitelyTyped/DefinitelyTyped/es6-shim/es6-shim.d.ts#7de6c3dd94feaeb21f20054b9f30d5dabc5efabd",
"jasmine": "github:DefinitelyTyped/DefinitelyTyped/jasmine/jasmine.d.ts#7de6c3dd94feaeb21f20054b9f30d5dabc5efabd"
}
}
有些 JS 庫擴充了 JavaScript 的語法與特性,但 TypeScript 編譯器並不認識,因此需要用 .d.ts 檔補上型別宣告,並在這裡註冊。
{
"name": "angular2-quickstart",
"version": "1.0.0",
"scripts": {
"start": "concurrently \"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.13",
"systemjs": "0.19.25",
"es6-shim": "^0.35.0",
"reflect-metadata": "0.1.2",
"rxjs": "5.0.0-beta.2",
"zone.js": "0.6.6"
},
"devDependencies": {
"concurrently": "^2.0.0",
"lite-server": "^2.1.0",
"typescript": "^1.8.9",
"typings": "^0.7.11"
}
}
安裝依賴:
npm install
過程中可能因為網路因素失敗,需要時可切換 npm 鏡像源。若出現 typings 相關錯誤,表示全域未安裝該工具:
npm install typings --global
npm start:同時啟動觀察模式編譯與 lite-servernpm run tsc:執行一次 TypeScript 編譯npm run tsc:w:觀察模式編譯,監控 .ts 檔變化並自動重新編譯npm run lite:啟動 lite-server,一個支援 Angular 路由的輕量靜態伺服器npm run typings:執行 typings 指令(依賴安裝時會透過 postinstall 自動跑一次)本文記錄的是 2.0 beta 時期的建置方式,當時官方文檔仍在快速演進。實際上手時請以 angular.io 的最新 quickstart 為準——2.0 正式版之後改用 npm + @angular/core 套件化發布,並引進了 Angular CLI,建置流程比這套手動配置簡便許多。理解這段歷史的價值,在於明白 Angular 為何需要 zone.js 與 reflect-metadata 這兩個看似古怪的依賴。