在eval期间移动偏移量(使用sourcemap)

我正在从一个文件中加载一个脚本,我正在使用eval()生成一个如下所示的Javascript代码:

 var code = fs.readFileSync('myfile'); var shiftedCode= 'function(param) {' + code + '}\n'+ '//# sourceURL=myfile'; eval(shiftedCode) 

问题是当我在代码中放置一个断点或debugging器时,它会在正确的一行之后停止两行,因为我想在开头添加字符。

有没有办法将sourceURL转移到正确的起点可能是使用源地图?

预先感谢您的帮助。

定义问题

我看到你正试图从一个页面导入Javascript代码到另一个页面,而且你正面临着一些问题(你定义了一个,我将定义另外一个):

  1. 源代码/debugging器问题
    • 首先 ,我不build议在运行时构build源代码。 像GulpGruntWebpack这样的工具可以帮助您处理这些用例,并让您专注于业务逻辑,并让您远离这些问题。
    • 其次想想一个人将在另一个页面使用此代码。 你认为转移源代码会好吗? 这将是每一个时间的转移!
    • 可能的解决scheme:这个lib也可以帮助你的使用情况。 先生成新的代码,然后运行它。
 var offsetLines = require('offset-sourcemap-lines'); var conv = require('convert-source-map'); var fs = require('fs'); var code = fs.readFileSync('myfile'); var originalMap = conv.fromSource(code).toObject(); var codeBody = conv.removeComments(code); var offsettedMap = offsetLines(originalMap, 1); // One line to be shifted var newSourceMapComment = conv.fromObject(offsettedMap).toComment(); var shiftedCode= 'function(param) {\n' + codeBody + '}\n' + newSourceMapComment; eval(shiftedCode) 

你可以使用下面的软件包offset-sourcemap-lines

 var offsetLines = require('offset-sourcemap-lines'); var conv = require('convert-source-map'); var fs = require('fs'); var codeWithSourceMapComment = fs.readFileSync('/path/to/code-with-sourcemap-comment.js', 'utf-8'); var originalMap = conv.fromSource(codeWithSourceMapComment).toObject(); var header = 'function(param) {' + code + '}\n'; var offset = header.match(/\n/g).length + 2; //you might need to work on this var offsettedMap = offsetLines(originalMap, offset); var codeBody = conv.removeComments(codeWithSourceMapComment); var newSourceMapComment = conv.fromObject(offsettedMap).toComment(); console.log(header + codeBody + '\n' + newSourceMapComment); 

那解决scheme呢? 而不是运行代码与eval使用Function constructor

myfile.js

 var a = 123; console.log(a, param1, param2); 

loader.js

 var code = fs.readFileSync('myfile.js'); var notShiftedCode = code + '\n//# sourceURL=myfile' var f = new Function('param1', 'param2', code2) f(456,678) 

我检查了铬devtool,它看起来非常尼特(用F11进入function)

我正在挖掘sourcemap的“部分”属性。 从规格,这可以通过设置起始偏移量来解决我的问题: https : //docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt

但主要的问题是,我找不到使用这个规范的debugging工具:似乎广泛实施或根本没有。

'offset-sourcemap-lines'是解决这个问题的有效手段,但是它也可以在合并期间偏移相关的源图。