源對映

Source map 是一種 JSON 檔案格式,它在瀏覽器接收到的已壓縮或已轉換的程式碼與其原始未修改的形式之間建立對映關係,以便在除錯時可以重建和使用原始程式碼。

瀏覽器執行的程式碼通常會經過一些轉換,使其與開發人員建立的原始原始碼不同。這有幾個原因:

  • 透過合併和壓縮原始檔,使從伺服器傳輸程式碼更有效率。
  • 透過將現代功能轉換為舊的等效功能,以支援舊版瀏覽器。
  • 使用瀏覽器不支援的語言,例如 TypeScriptSass

在這些情況下,除錯原始原始碼比除錯瀏覽器已下載的轉換後的原始碼要容易得多。瀏覽器透過資源的 SourceMap HTTP 標頭或生成程式碼中的 sourceMappingURL 註釋來檢測 source map。

示例

例如,考慮 Sass 的 SCSS 語法:

scss
ul {
  list-style: none;
  li {
    display: inline;
  }
}

在構建過程中,SCSS 會被轉換為 CSS。會生成一個 source map 檔案 index.css.map,並在 CSS 末尾的註釋中連結到它。

css
ul {
  list-style: none;
}
ul li {
  display: inline;
}

/*# sourceMappingURL=index.css.map */

此對映檔案不僅包含原始 SCSS 和生成的 CSS 之間的對映,還以編碼形式包含原始 SCSS 原始碼。它會被瀏覽器的 CSS 解析器忽略,但會被瀏覽器的 DevTools 使用。

json
{
  "version": 3,
  "sourceRoot": "",
  "sources": ["index.scss"],
  "names": [],
  "mappings": "AAAA;EACC;;AACA;EACC",
  "file": "index.css"
}

Source map 允許瀏覽器的 DevTools 連結到原始 SCSS 檔案中的特定行並顯示原始碼。

Firefox DevTools focused on the li element in the DOM inspector. The style panel shows transformed CSS without nesting and a link to the third line of the index.scss file.

Firefox DevTools with the index.scss file opened in the style editor. The editor is focused on the source code's third line in SCSS format with nesting.

另見