sajad torkamani

What is a source map?

A source map is a JSON file that maps between compiled code received by the browser and its original uncompiled form, allowing the original source code to be reconstructed for debugging purposes.

Code received and executed by the browser is often transformed and minified from its original form by tools like Vite or Webpack. This might be to make the files smaller, transform modern JavaScript syntax to into a form that older browsers support or to compile languages like TypeScript or Sass into a format the browser understands.

A source map file ends with .map (e.g., main.min.js.map or main.css.map). You can generate them with most build tools like Vite, Webpack, Rollup, etc.

For example, you can configure Vite to generate source maps like so:

/* Example configuration: vite.config.js */
/* https://vitejs.dev/config/ */

export default defineConfig({
  build: {
    sourcemap: true, // enable production source maps
  }
})

Example

A source map is a JSON file that looks like this:

{
  "mappings": "AAAAA,SAASC,cAAc,WAAWC, ...",
  "sources": ["src/main.ts"],
  "sourcesContent": ["document.querySelector('button')..."],
  "names": ["document","querySelector", ...],
  "version": 3,
  "file": "main.min.js.map"
}

That file helps browser dev tools like Chrome’s DevTools to map any line in the compiled code back to the equivalent line in the original code. See here for more details about each of those fields but the main field is the mappings field which uses a VLQ base-64 encoded string to map lines and locations in the compiled code back to the original code.

The source map means that:

  • A JavaScript exception’s stack trace will point to lines in the original source code instead of the compiled code. Browsers use the source map files to map this for you.
  • When you’re viewing the CSS for an HTML element where the original code was written in SASS, the browser’s dev tools points to styles defined in the original SASS code, not the minified CSS. Again, browsers use source map files to do this mapping.

Other notes

  • Browsers only download .map files when DevTools is open which means normal users don’t have to download extra data.
Tagged: Misc