Search code examples
javascriptgoogle-chrome-devtoolssource-maps

Is it possible to use sourcemaps for inline Javascript in HTML?


Is it possible to use data-URI source-maps in inline Javascript in HTML script tags?

I've tried a few variations on the following HTML, but none of them seem to produce a usable sourcemap for the embedded JS when the page is loaded in Chrome:

<script type="text/javascript">
/* source code... */

//# sourceMappingURL=data:application/json;base64,/* base64'd inline sourcemap */
</script>

I've also tried stripping sourcesContent, file, and sourceRoot from the generated sourcemap, since I figure those wouldn't apply in this situation. But it doesn't seem to help.

The spec seems to imply that this is possible, or at least considered, since script tags without src attributes are briefly mentioned:

If the generated code is associated with a script element and the script element does not have a “src” attribute, then the source origin will be the page’s origin.

https://sourcemaps.info/spec.html

However, I am having trouble finding evidence of this being used in the wild, or if this is even possible. Can anyone help shed some light on this?


Solution

  • With inlined scripts, it is possible to add inlined sourcemaps too. It is done as you state above. Although type="text/javascript" is optional.

    <script type="text/javascript">
    /* source code... */
    
    //# sourceMappingURL=data:application/json;base64,/* base64'd inline sourcemap */
    </script>
    

    The issue I had after inlining the sourcemap was that my inlined script was nameless. So when trying to debug in Chrome Dev Tools, I was unable to open the script in the Sources tab to set debug points. I could not find the script at all. Even checking the HTML page where the scripts are embedded did not help as the inlined scripts are not part of the original HTML source. The inlined scripts are added after the HTML is loaded. I believe this is how PreloadJS loads JavaScript via XHR.

    To solve this, you can use //# sourceURL=someFile.js which will apply the name "someFile.js" to your inlined script. You could use any name here, it does not need to be the name of the original source.

    Now when you search in Sources tab you will find the script as "someFile.js", you can set debug points and you will be directed to the original source file, provided your sourcemap is correct before base64 encoding.

    Below is a link to a resource that describes the behaviour of sourceURL. The entire article is actually really interesting. If you have 5 mins, give it a read. https://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl

    This MDN article also shows the use of the sourceURL, albeit in eval'd JS code.