简体   繁体   中英

Source map for a dynamically created function

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM