Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Source map for a dynamically created function

Tags:

javascript

JavaScript allows you to create new functions at runtime with the new Function(...) or eval. Is it possible for a function created in this way to set something like a source map? That is, set the name of the source file from which it was allegedly loaded, as well as different source line numbers.

If there is no general solution, then there may be particular solutions for specific JavaScript engines.

like image 912
kiv_apple Avatar asked Mar 24 '18 09:03

kiv_apple


People also ask

How to enable enable JavaScript source maps?

Browser support To enable source maps in Google Chrome, go to Developer Tools, click the little cog icon, and then make sure that “Enable Javascript source maps” is checked. That's it.

What is source map in CSS?

A “source map” is a special file that connects a minified/uglified version of an asset (CSS or JavaScript) to the original authored version.

What is source map in Webpack?

In a sense, source maps are the decoder ring to your secret (minified) code. Using Webpack, specifying devtool: "source-map" in your Webpack config will enable source maps, and Webpack will output a sourceMappingURL directive in your final, minified file.


1 Answers

For eval'd code you can simply add:

//# sourceMappingURL=<url>
//# sourceURL=<filename.js>

To the bottom of the code you are evaluating. For the sourceMappingURL, you will send in a data url, since naturally you don't have an existing source map hosted somewhere and you will be dynamically generating it.

Place your original source in the sourcesContent field in the source map, set the file field in the source map to whatever you set in sourceURL, and you should be good to go.

My current attempts at getting this to work in Function constructors is failing, which is a shame- in this case, in both Edge and Chrome, the original source is correctly listed, but it appears that the line number information is broken (the instruction pointer always points to the last line). I am currently investigating this. However, the source map spec does allude to Function constructors containing sourcemaps:

If the generated code is being evaluated as a string with the eval() function or via new Function(), then the source origin will be the page’s origin.

This leads me to believe either I am doing something silly, or there is not great support for this feature.

like image 175
mseddon Avatar answered Oct 09 '22 00:10

mseddon