LearnAn Introduction to Source Maps

Matt West
writes on December 12, 2013

One of the easiest performance wins you can gain for your website is to combine and compress your JavaScript and CSS files. But what happens when you need to debug the code within those compressed files? It can be a nightmare. Fear not however, there is a solution on the horizon and it goes by the name of source maps.

A source map provides a way of mapping code within a compressed file back to it’s original position in a source file. This means that – with the help of a bit of software – you can easily debug your applications even after your assets have been optimized. The Chrome and Firefox developer tools both ship with built-in support for source maps.

In this blog post you’re going to learn how source maps work and take a look at how to generate them. We’re going to be focussing primarily on source maps for JavaScript code but the principles apply to CSS source maps too.


Note: Support for source maps is enabled by default in Firefox’s developer tools. You may need to enable support manually in Chrome. To do this, launch the Chrome dev tools and open the Settings pane (cog in the bottom right corner). In the General tab make sure that Enable JS source maps and Enable CSS source maps are both ticked.


How Source Maps Work

As the name suggests, a source map consists of a whole bunch of information that can be used to map the code within a compressed file back to it’s original source. You can specify a different source map for each of your compressed files.

You indicate to the browser that a source map is available by adding a special comment to the bottom of your optimised file.

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

This comment will usually be added by the program that was used to generate the source map. The developer tools will only load this file if support for source maps is enabled and the developer tools are open.

You can also specify a source map is available by sending the X-SourceMap HTTP header in the response for the compressed JavaScript file.

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

The source map file contains a JSON object with information about the map itself and the original JavaScript files. Here is a simple example:

{
    version: 3,
    file: "script.js.map",
    sources: [
        "app.js",
        "content.js",
        "widget.js"
    ],
    sourceRoot: "/",
    names: ["slideUp", "slideDown", "save"],
    mappings: "AAA0B,kBAAhBA,QAAOC,SACjBD,OAAOC,OAAO..."
}

Lets take a closer look at each of these properties.

  • 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.)

Are you ready to start learning?

Learning with Treehouse for only 30 minutes a day can teach you the skills needed to land the job that you’ve been dreaming about.

Start a Free Trial

Two people working on a computer

Generating Source Maps with UglifyJS

UglifyJS is a popular command line utility that allows you to combine and compress JavaScript files. Version 2 supports a number of command line flags that help with generating source maps.

  • --source-map – The output file for the source map.
  • --source-map-root – (optional) This populates the sourceRoot property in the map file.
  • --source-map-url – (optional) The path to the source map on your server. This will be used in the comment that is placed in the optimized file. //# sourceMappingURL=/path/to/script.js.map
  • --in-source-map – (optional) An input source map. This can be useful if you are compressing JavaScript files that have already been generated from source files elsewhere. Think JavaScript libraries.
  • --prefix or -p – (optional) Removes n number of directories from the file paths that appear in the sources property. For example, -p 3 would drop the first three directories from the file path, so one/two/three/file.js would become file.js. Using -p relative will make UglifyJS figure out the relative paths between the source map and the original files for you.

Here’s an example command that uses some of these command line flags.

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

Note: If you use the grunt-contrib-uglify plugin for Grunt, refer to the documentation for information on how to specify these options in your Gruntfile.


There are also a number of other utilities available that have support for generating source maps. A selection of these are listed below.

Source Maps in Chrome Dev Tools

The Sources Tab in Chrome Dev Tools

The Sources Tab in Chrome Dev Tools

If you have your source maps set up correctly, you should see each of the original JavaScript files listed in the file pane of the Sources tab.

Examining the HTML for your page will confirm that only the compressed JavaScript file is being referenced. The dev tools is loading the source map file for you and then fetching each of the original source files.

Try a Demo

Source Maps in the Firefox Developer Tools

The Debugger Tab in the Firefox Developer Tools

The Debugger Tab in the Firefox Developer Tools

Firefox users can see the individual source files in the Debugger tab of the developer tools. Again the dev tools has identified that a source map is available and has then fetched each of the referenced source files.

Should you wish to view the compressed versions instead, click the cog icon in the top right corner of the tab and deselect Show original sources.

Try a Demo

Final Thoughts

Using source maps allows developers to maintain a straight-forward debugging environment while at the same time optimizing their sites for performance.

In this post you have learned how source maps work and seen how you can generate them using UglifyJS. If you ever ship websites with compressed assets (which you should), it’s really worth taking the time to integrate source map creation into your workflow.

Useful Links

12 Responses to “An Introduction to Source Maps”

  1. Henrik Östman on March 30, 2017 at 4:33 am said:

    file: “script.js.map”
    should’nt it be “file: “script.js”?

    File should name the minified javascript file, not the sourcemap one.
    Look at jQuery för example:
    http://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.map

  2. Vivek Marakana on November 3, 2016 at 11:54 pm said:

    Can you tell me how to reverse this process i.e. generate original from minified file and source-map?

  3. I am using source map concepts in my application.But I am not able debugging perfectly(breakpoints not set many of the places).

    How can I achieve this?

  4. Demo does not seems to be working, compressed javascript shows in page itself rather uncompressed as separate as you mentioned

  5. Am I mistaken or has the source-maps demo been optimized after you published it? There are no more source files loaded. Instead, all JS is merged and embedded into the HTML page directly.

    Regards, Frank

  6. Emily Bonnett on December 22, 2015 at 8:59 pm said:

    You can easily debug your applications even after your assets have been optimized. The Chrome and Firefox developer tools both ship with built-in support for source maps.

  7. This is trivial but just want to point out a spelling mistake. In “Generating Source Maps with UgilfyJS” (UgilfyJS => UglifyJS)

  8. According to the spec:

    > Line 3: An optional name of the generated code that this source map is associated with.

    So, instead of `script.js.map`, perhaps it should read `script.js`?

    Regards

    • Hi Jorge,

      I think that line is referring to the name of the main file, not the source map file.

      • I think Jorge was referring to the name “script.js.map” in your simple example (line 2 of the JSON object). Since line 2 of the JSON object provides the name of the file with the generated code it should be “script.js”.

        The specs state that “Optionally, a source map will have the same name as the generated file but with a “.map” extension.”. You used that naming convention in this post when you used the name “script.js.map” for the source map in “//# sourceMappingURL=/path/to/script.js.map” and “X-SourceMap: /path/to/script.js.map”.

        Regards

Leave a Reply

You must be logged in to post a comment.

Want to learn more about CSS?

Learn how CSS allows you to apply visual styling to HTML elements with colors, fonts, layouts, and more.

Learn more