Angular - 網站啟動流程說明

  • 991
  • 0
  • 2018-05-08

針對Angular2的網站啟動流程做一個簡單的說明

透過Angular CLI指令: ng new 專案名稱  開啟一個全新的Angular網站後,

打開檔案angular-cli.json

"apps": [
    {
      "root": "src",
      "outDir": "dist",
      "assets": [
        "assets",
        "favicon.ico"
      ],
      "index": "index.html",
      "main": "main.ts",
      "polyfills": "polyfills.ts",
      "test": "test.ts",
      "tsconfig": "tsconfig.app.json",
      "testTsconfig": "tsconfig.spec.json",
      "prefix": "app",
      "styles": [
        "styles.css"
      ],
      "scripts": [],
      "environmentSource": "environments/environment.ts",
      "environments": {
        "dev": "environments/environment.ts",
        "prod": "environments/environment.prod.ts"
      }
    }
  ],

可看到屬性"index" 是打開index.html (預設開啟的首頁)

屬性"main" 是啟動main.ts (預設載入的TS)

 

在檔案:main.ts內 ,可看到啟動Module(bootstrapModule)是 AppModule

點選AppModule之後,按F12,可自動開啟檔案app.module.ts

在檔案app.module.ts內可以 看到啟動的component是 AppComponent

針對 AppComponent 再點F12可開啟檔案 app.component.ts 

裡面的內容如下:

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app';
}

@Component 這個decorator內有三個屬性

selector : 選取器,其他的component如要使用這個component,在html內要這樣寫selector 定義的值,

                例如 可以在index.html 內看到 <app-root></app-root>

templateUrl : component 的 template 路徑在哪裡(也就是HTML)

styleUrls : component 會使用的 css 檔案路徑

 

文章一開始的時候有提到的檔案:angular-cli.json

"index": "index.html",

打開index.html 可以看到使用<app-root></app-root>

所以現在畫面上看到的 <app-root></app-root> 底下的 html 元件,都是定義在app.component.html 裡面

 

在Angular內JS的匯入:

目前在index.html內完全沒有看到js的引用,

使用CLI指令 ng serve 將專案on起來之後,

可以看到 webpack 將js 建置打包起來 匯入到網頁之中

打開Chrome 連線到:http://localhost:4200/ 之後,滑鼠右鍵 檢視網頁原始碼

可以看到開啟的網頁所需要使用的js已經都匯入了。