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.
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.
A “source map” is a special file that connects a minified/uglified version of an asset (CSS or JavaScript) to the original authored version.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With