DIV CSS 佈局教程網

AngularJS 2.0 快速開始:開發環境建置指南
編輯:JavaScript基礎知識     

AngularJS 2.0 是一場徹底的重新設計,它基於 TypeScript 開發,模塊系統與裝飾器語法都和 1.x 差異極大。本文整理官方 quickstart 的環境建置流程,適合第一次接觸 2.0 的開發者。

前置需求:機器上需有 Node.js 環境。2.0 以 TypeScript 撰寫,因此還需要 tsc 編譯器與 typings 型別定義工具。

一、建立專案資料夾

mkdir angular2-quickstart
cd angular2-quickstart

二、tsconfig.json:TypeScript 編譯設定

{
  "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 原始碼

三、typings.json:型別定義檔

{
  "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 檔補上型別宣告,並在這裡註冊。

四、package.json:依賴與腳本

{
  "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-server
  • npm run tsc:執行一次 TypeScript 編譯
  • npm run tsc:w:觀察模式編譯,監控 .ts 檔變化並自動重新編譯
  • npm run lite:啟動 lite-server,一個支援 Angular 路由的輕量靜態伺服器
  • npm run typings:執行 typings 指令(依賴安裝時會透過 postinstall 自動跑一次)

六、各依賴的作用

  • angular2:框架本體
  • systemjs:瀏覽器端模塊載入器,負責按需載入 ES6 模塊
  • es6-shim:為舊瀏覽器補上 Promise、Map 等 ES6 特性
  • reflect-metadata:讓 TypeScript 的裝飾器中介資料能在運行期被讀取,是依賴注入的基礎
  • rxjs:Reactive Extensions for JavaScript,2.0 用它處理非同步資料流
  • zone.js:執行環境監控,讓框架能感知所有非同步任務並觸發變更偵測

後記

本文記錄的是 2.0 beta 時期的建置方式,當時官方文檔仍在快速演進。實際上手時請以 angular.io 的最新 quickstart 為準——2.0 正式版之後改用 npm + @angular/core 套件化發布,並引進了 Angular CLI,建置流程比這套手動配置簡便許多。理解這段歷史的價值,在於明白 Angular 為何需要 zone.js 與 reflect-metadata 這兩個看似古怪的依賴。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved