What's inside a source map, and why you can't just glue two together
A bundler minifies each file and joins the results. Joining the JavaScript is one line of code. Joining the source maps that came with it is the step that’s easiest to get subtly wrong. The bundle runs fine and devtools opens without complaint, but every breakpoint after the first file lands in the wrong place.
To see why, you have to look inside a map.
what a map holds
Take a small file and its minified output:
function add(first, second) {
return first + second;
}function add(n, d) {
return n + d;
}Its source map is a JSON file:
{
"version": 3,
"file": "a.min.js",
"sources": ["a.js"],
"names": ["add", "first", "second"],
"mappings": "AAAA,SAASA,IAAIC,EAAOC,GAClB,OAAOD,EAAQC"
}sources lists the original files and names lists original identifiers. Everything else is in mappings, which links positions in the minified file to positions in the originals.
reading the mappings string
mappings is split into lines by ;, one group per line of generated code. This file is one line, so there’s no ;. Each line is split by , into segments, and each segment is a run of numbers:
| field | meaning |
|---|---|
| 1 | column in the generated line |
| 2 | index into sources |
| 3 | line in that source |
| 4 | column in that source |
| 5 | index into names (optional, for a renamed symbol) |
A segment has 1, 4 or 5 fields. A 1-field segment marks generated code that comes from no source. All positions are zero-based.
Decoded, the map above says:
| segment | decoded | means |
|---|---|---|
AAAA |
[0, 0, 0, 0] |
column 0 is a.js line 0, column 0: function |
SAASA |
[9, 0, 0, 9, 0] |
column 9 is a.js 0:9, named add |
IAAIC |
[4, 0, 0, 4, 1] |
column 13 is a.js 0:13, named first. That’s the n. |
EAAOC |
[2, 0, 0, 7, 1] |
column 15 is a.js 0:20, named second. That’s the d. |
GAClB |
[3, 0, 1, -18] |
column 18 is a.js 1:2: return |
Look at the third row. The n is at column 13, but the segment says 4, and its name index says 1 when first is at index 1 and second at 2. Every field is a delta from the previous segment. Column 13 is 9 + 4. Name 1 is 0 + 1. The -18 in the last row takes the original column from 20 back to 2, because return is on the next source line, near its start.
The rule that matters later: the generated column resets to zero at each new line (each ;), but the other four fields never reset. They carry on from the last segment that had them, across the whole map.
Deltas keep the numbers small, and small numbers encode in fewer characters.
Base64 VLQ in one paragraph
Each number is written as a variable-length quantity in Base64. A Base64 character carries 6 bits. The top bit says “another character follows”, and the other 5 are data, least significant group first. In the first character, the lowest data bit is the sign. So 0 is A, 1 is C, -1 is D, and 16 needs two characters: 16 shifted left for the sign bit is 32, the low five bits (00000) go first with the continuation bit set (g), and the remaining 1 follows (B). That gives gB. Most deltas in a map fit in one character, which is why a mappings string looks like AAAA,SAASA,IAAIC.
gluing two maps together
Now a second file:
const greeting = 'hi';
console.log(greeting);{
"version": 3,
"sources": ["b.js"],
"names": ["greeting"],
"mappings": "AAAA,MAAMA,OACN,YAAYA"
}The bundle is the two minified files joined with ; and a newline (the semicolon is there for automatic semicolon insertion):
function add(n, d) {
return n + d;
}
const o = 'hi';
console.log(o);The obvious combined map concatenates the arrays and joins the two mappings strings with a ;, since b’s code starts on the next line:
{
"version": 3,
"sources": ["a.js", "b.js"],
"names": ["add", "first", "second", "greeting"],
"mappings": "AAAA,SAASA,IAAIC,EAAOC,GAClB,OAAOD,EAAQC;AAAA,MAAMA,OACN,YAAYA"
}It’s valid JSON, it parses, and it’s wrong. Asking a decoder where line 2 of the bundle comes from:
| bundle position | should be | the glued map says |
|---|---|---|
| line 2, col 0 | b.js 1:0 |
a.js 2:17 |
| line 2, col 6 | b.js 1:6 greeting |
a.js 2:23, named second |
| line 2, col 25 | b.js 2:12 greeting |
a.js 3:29, named second |
(Lines here are one-based, as an editor shows them.) Every position in the second file points into the first, at lines and columns a.js doesn’t even have.
The deltas explain it. b’s first segment, AAAA, means “same source, same line, same column as before”. In its own map, “before” was the starting state: source 0, line 0, column 0. In the glued map, “before” is a’s last segment: source 0 (a.js), line 1, column 17. So b’s code lands in a.js, starting just past where a left off. Name indices drift the same way: b’s name delta of 0 lands on second instead of greeting.
You can’t fix that by editing the strings. Every segment after the join point would have to change.
doing it properly: decode, shift, re-encode
The reliable way is to work on decoded numbers, not strings:
- Decode each map’s
mappingsto absolute values. - Shift the second map’s source indices by the length of the first map’s
sources, and its name indices by the length of itsnames. - Shift its generated lines by however many lines come before it in the bundle.
- Encode the whole thing again as one continuous sequence of deltas.
For the example, only b’s first segment changes:
glued: …,EAAQC;AAAA,MAAMA,OACN,YAAYA
correct: …,EAAQC;ACDjB,MAAMC,OACN,YAAYAACDjB reads: column 0, next source (+1), back one line (−1), back 17 columns (jB is −17). That’s the step from a’s last segment to b.js line 0, column 0. The rest of b’s segments were already relative to that one, so they stay the same, except MAAMC, whose name delta becomes +1 to step from second to greeting.
Step 3 is where real bundles go wrong, because the line count has to include every line in the output, not just the minified code:
- Separators. Each newline you put between files adds a generated line, so it needs a
;in the mappings. - Files that aren’t minified again. A
.min.jsfrom a vendor, passed through as it is, has no mappings, but its lines are still in the bundle. Write an empty group (;) for each one, or every file after it is off by its line count. - Per-file
sourceMappingURLcomments. A minifier run on one file usually ends it with//# sourceMappingURL=a.min.js.map. In a bundle, that line points at a map nobody serves and adds a line the combined map has to account for. Turn the comment off per file and write one at the end of the bundle.
or don’t merge at all: index maps
The format has a second shape for exactly this case. An index map has no mappings of its own. Instead it lists sections, each placing a complete map at an offset in the generated file:
{
"version": 3,
"file": "app.js",
"sections": [
{ "offset": { "line": 0, "column": 0 }, "map": { "sources": ["a.js"], "…": "…" } },
{ "offset": { "line": 1, "column": 0 }, "map": { "sources": ["b.js"], "…": "…" } }
]
}Each section’s deltas start fresh, so the per-file maps go in unchanged and the bundler only tracks line offsets. It’s part of the format, now standardized as ECMA-426. Before you ship one, check that every tool that reads your maps accepts index maps: browser devtools, your error tracker, anything that symbolicates stack traces. If you can’t check them all, flatten into one map as above. Every consumer reads that.
finding the map, and the files behind it
Two URLs in a map are resolved relative to different things:
- The
//# sourceMappingURL=comment (or aSourceMapresponse header) is resolved against the script’s URL. - Each entry in
sourcesis resolved against the map’s URL, aftersourceRootis prepended if there is one.
If either is written as a root-absolute path (/js/a.js), it breaks as soon as the app is served under a prefix, such as https://example.com/myapp/. Devtools then asks for https://example.com/js/a.js, gets a 404 and shows the minified code. Relative paths work under any prefix. If the original files aren’t served at all, sourcesContent embeds their text in the map instead.
testing it
A map that’s wrong in the middle passes every check that only looks at its shape. The useful test is the one in this post: pick tokens in the bundle, ask a decoder where they came from, and compare with the source. In JavaScript, @jridgewell/trace-mapping does this with originalPositionFor. Check one token from the first file, one from the last, and one from just after a file that was passed through unminified. Those three cover the mistakes above.
