如何使用源映射隐藏来自已转换代码的函数调用?

Nat*_*all 10 javascript source-maps

假设我的语言看起来像

print "Hello World"
Run Code Online (Sandbox Code Playgroud)

这转化为

var $__Helpers = {
    print: function(s) {
        if (typeof s != 'string')
            throw new TypeError('String expected');
        console.log(s);
    }
};

$__Helpers.print("Hello World");
Run Code Online (Sandbox Code Playgroud)

如果这种语言的用户这样做

print 5
Run Code Online (Sandbox Code Playgroud)

通过$__Helpers.print说"String expected" 将抛出TypeError .我希望开发人员工具将该print 5行显示为此错误的原始调用.我知道如何让我的源地图显示一个看起来像的调用堆栈

transpiled_script.js:2
original_script.os:1
Run Code Online (Sandbox Code Playgroud)

transpiled_script.js:2调用$__Helpers.print函数的脚本和行号在哪里,是调用original_script.os:1的脚本和行号print 5.我想让开发工具忽略顶部调用transpiled_script.js(这只是我的转换程序的一个实现细节)并且只显示来自原始脚本的调用(这是他们应该在自己的脚本中调试的部分).

我显然不能简单地映射transpiled_script.js:2original_script.os:1因为print内部可能有多个调用original_script.os,所以它不是一对一的关系.

有没有办法做到这一点?

(我使用escodegen来生成我的源码和我的源码图(escodegen使用Node mozilla/source-map模块),所以有办法告诉escodegen或mozilla/source-map这样做是理想的,但我可以覆盖escodegen的输出,如果这是不可能的.)

Oha*_*hen 3

您可以分割跟踪并打印所需的行

var $__Helpers = {
    print: function(s) {
        if (typeof s != 'string'){
            var err = new TypeError('String expected');
            var trace = err.stack.split('\n')
            console.error(trace[0]); // TypeError: string expected
            console.error(trace[2]); // the line who called the function, probably 
            //original_script.os:1, or whatever line number the call was from
            //quit the script

        }
        console.log(s);
    } };
Run Code Online (Sandbox Code Playgroud)

编辑:更好的解决方案是替换错误的跟踪,而不是抛出错误,代码现在如下所示:

var $__Helpers = {
    print: function(s) {
        if (typeof s != 'string'){
            var err = new TypeError('String expected: Got'+s);
            err.stack = err.stack.replace(/\n.*transpiled_script\.js.*?\n/g,"\n");
            throw err;

        }
        console.log(s);
    } };
Run Code Online (Sandbox Code Playgroud)

这也适用于嵌套调用中的错误。