前端随笔:SourceMap

182 阅读1分钟

Source Maps

JavaScript 语言级的功能,帮助我们映射编译后的代码到源码,以追踪错误;

Chrome / Firefox devTools 支持这项功能;

A source map provides a way of mapping code within a compressed file back to it’s original position in a source file.

But how source map works?

在发布文件的底部,加入一行特殊注释,指定 SourceMap 文件的路径;

//# sourceMappingURL=/path/to/script.js.map

或者,在返回 JS 文件的返回头上,加上 X-SourceMap 属性:

X-SourceMap: /path/to/script.js.map

SourceMap 文件,就是一个 JSON, 包含 Map 本身,及关联关系的信息:

{
    version: 3,
    file: "script.js.map",
    sources: [
        "app.js",
        "content.js",
        "widget.js"
    ],
    sourceRoot: "/",
    names: ["slideUp", "slideDown", "save"],
    ......
   

属性的解释是这样的:

  • version – This property indicates which version of the source map spec the file adheres to.
  • file – The name of the source map file.
  • sources – An array of URLs for the original source files.
  • sourceRoot – (optional) The URL which all of the files in the sources array will be resolved from.
  • names – An array containing all of the variable and function names from your source files.
  • mappings – A string of Base64 VLQs containing the actual code mappings. (This is where the magic happens.)

那么,这个 .js.map 文件又是怎么来的呢?这是 UglifyJS 库生成的

uglifyjs [input files] -o script.min.js --source-map script.js.map --source-map-root http://example.com/js -c -m

又或者我们使用 Webpack 构建工具,可以在配置里的选项 devtools 配置 SourceMap 的行为:

    module.exports = {
    entry: {
      app: './src/index.js',
      print: './src/print.js'
    },
+   devtool: 'inline-source-map',
    ......