Source Map Basics — Debug Minified Code
Learn how source maps work to map minified production code back to original source files. Covers source map generation, formats, security considerations, and debugging workflows.
Detailed Explanation
How Source Maps Work
Source maps are JSON files that create a mapping between minified/compiled production code and the original source code. They allow browser DevTools to display and debug the original source even when the deployed code is minified.
The Source Map File
A source map file (.map) contains:
{
"version": 3,
"file": "app.min.js",
"sourceRoot": "",
"sources": ["src/app.ts", "src/utils.ts"],
"names": ["calculateTotal", "items", "taxRate"],
"mappings": "AAAA,SAAS,EAAO..."
}
Key fields:
version— Always 3 (the current spec version).sources— Array of original source file paths.names— Array of original identifier names (before mangling).mappings— Base64 VLQ-encoded string mapping each position in the output to a position in the original source.
How the Browser Finds Source Maps
The minified file includes a special comment pointing to the map:
// app.min.js
function a(t,e){return t*e}
//# sourceMappingURL=app.min.js.map
Or via an HTTP header:
SourceMap: /maps/app.min.js.map
When DevTools detects this, it fetches the map file and reconstructs the original source for display.
Generating Source Maps
Every major minifier and bundler can generate source maps:
- Terser:
--source-mapflag orsourceMap: truein options - webpack:
devtool: 'source-map'(multiple modes available) - Vite:
build.sourcemap: true - esbuild:
--sourcemapflag
Security Considerations
Source maps expose your original source code. In production:
- Do not deploy source maps publicly unless your code is open-source.
- Use hidden source maps (
devtool: 'hidden-source-map'in webpack) — generates the file but omits thesourceMappingURLcomment. - Upload to error tracking services — Sentry, Datadog, and Bugsnag accept source maps privately to decode error stack traces.
- Restrict access via server configuration (only allow internal IPs or authenticated users).
Source Maps for CSS
CSS minifiers also generate source maps, allowing DevTools to show the original stylesheet location (including SCSS/Less source files) when inspecting styles.
Use Case
Source maps are essential for any team that minifies production code. They enable debugging production issues without deploying unminified code, and they allow error monitoring services to provide meaningful stack traces that reference original source file names and line numbers.