JavaScript 源映射的内部工作原理

Source maps are the main piece in the jigsaw puzzle of mapping symbols and locations from "built" JavaScript files back to the original source code. When you debug minified JavaScript in your browser's DevTools and see the original source with proper variable names and formatting, you're witnessing source maps in action.

源映射是将“构建”JavaScript 文件中的符号和位置映射回原始源代码的拼图中的主要部分。当您在浏览器的开发者工具中调试压缩的 JavaScript 并看到带有正确变量名称和格式的原始源代码时,您就是在目睹源映射的实际应用。

For example, when your browser encounters an error at bundle.min.js:1:27698, the source map translates this to src/index.ts:73:16, revealing exactly where the issue occurred in your original TypeScript code:

例如,当您的浏览器在 bundle.min.js:1:27698 遇到错误时,源映射将其转换为 src/index.ts:73:16,准确揭示了问题在您原始 TypeScript 代码中的发生位置:

But how does this actually work under the hood? In this post, we'll take a deep dive into the internals of source maps, exploring their format, encoding mechanisms, and how devtools use them to bridge the gap between production code and developer-friendly sources.

但这实际上是如何在后台工作的呢?在这篇文章中,我们将深入探讨源映射的内部结构,探索它们的格式、编码机制,以及开发工具如何使用它们来弥合生产代码与开发者友好源之间的差距。

The TypeScript Build Pipeline

TypeScript 构建管道

Modern JavaScript builds typically involve three main stages:

现代 JavaScript 构建通常涉及三个主要阶段:

  • Transpilation: TypeScript → JavaScript
  • 转译:TypeScript → JavaScript
  • Bundling: Combining modules into a single file
  • 打包:将模块组合成一个文件
  • Minification: Compressing code for production
  • 压缩:为生产压缩代码

At each stage, source maps preserve the connection back to the original code.

在每个阶段,源映射保留了与原始代码的连接。

The original TypeScript source files with full type annotations.

带有完整类型注释的原始TypeScript源文件。

add.ts

add.ts

1export function add(a: number, b: number): number {

1export function add(a: number, b: number): number {

2 return a + b;

2 return a + b;

3}

3}

fibonacci.ts

fibonacci.ts

1import { add } from './add';

1import { add } from './add';

2

2

3export function computeFibonacci(n: number): number {

3export function computeFibonacci(n: number): number {

4 if (n <= 1) return n;

4 如果 (n <= 1) 返回 n;

5 return add(computeFibonacci(n - 1), computeFi...

开通本站会员,查看完整译文。

首页 - Wiki
Copyright © 2011-2025 iteam. Current version is 2.147.1. UTC+08:00, 2025-11-09 04:28
浙ICP备14020137号-1 $访客地图$