iT邦幫忙

0

Angular good practice - 前端工程師都應該了解的source maps

WM 2020-04-19 12:29:53564 瀏覽

目前情境:
按下Add Server,會將資料塞入陣列中,並在畫面上以列表的型式表現。

這是一個有邏輯錯誤的程式,會刪除所選取的下一個Another Server,開發者工具的Console也沒有錯誤產生,那我們要如何得知在操作過程中,變數的值是多少,方便除錯?
https://ithelp.ithome.com.tw/upload/images/20200419/20112573cuLLatgWAq.png
template:

<div class="container">
  <div class="row">
    <div class="col-12">
      <h2>My Servers</h2>
      <button class="btn btn-primary" (click)="onAddServer()">Add Server</button>
      <br>
      <div class="list-group mt-3">
        <a class="list-group-item list-group-item-action" style="cursor: pointer;"
          *ngFor="let server of servers; let idx =index" (click)="onRemoveServer(idx)">
          {{ server }}
        </a>
      </div>
    </div>
  </div>
</div>

component:

idx = 0;
servers = [];
onAddServer() {
  this.servers.push(`Another Server ${this.idx}`);
  this.idx++;
}
onRemoveServer(id: number) {
  const position = id + 1;
  this.servers.splice(position, 1);
}

這時可以利用source maps的功能:
https://ithelp.ithome.com.tw/upload/images/20200419/201125731vj0zZSEWM.png

滑鼠點選第17行:
https://ithelp.ithome.com.tw/upload/images/20200419/20112573E0nOSC0hKz.png

執行刪除Another Server 0,畫面顯示如下:
https://ithelp.ithome.com.tw/upload/images/20200419/20112573ob02YWfE6K.png

目前id為0:
https://ithelp.ithome.com.tw/upload/images/20200419/20112573QtdmsJLStM.png

F10,跳到下一行程式執行,position為1,問題就出在這,由於position=id+1,因此所刪除的會是下一個元素:
https://ithelp.ithome.com.tw/upload/images/20200419/20112573XYBwb5cW74.png

再按F10,這時已經取得變數的結果了:
https://ithelp.ithome.com.tw/upload/images/20200419/20112573W5zKI7WrKu.png

F8,完成這次方法的執行,結果如預料的,並非我們想刪除的項目:
https://ithelp.ithome.com.tw/upload/images/20200419/20112573FFYqwLvwuV.png
position=id+1拿掉,就是我們要的邏輯。

source maps是什麼?

簡單說,source maps就是一個信息文件,裡面儲存著位置信息。也就是說,轉換後的代碼的每一個位置,所對應的轉換前的位置。
有了它,出錯的時候,除錯工具將直接顯示原始代碼,而不是轉換後的代碼。這無疑給開發者帶來了很大方便。

開啟開發人員工具 > 設定:
https://ithelp.ithome.com.tw/upload/images/20200418/20112573LwDawnvRUa.png

預設是開啟的:
https://ithelp.ithome.com.tw/upload/images/20200418/20112573HELfu4Bf1t.png

參考來源:
JavaScript Source Map 詳解
Angular - The Complete Guide (2020 Edition)


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言