源映射

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.

另见