javascript – 如何使用源地图隐藏来自泛型代码的函数调用?

前端之家收集整理的这篇文章主要介绍了javascript – 如何使用源地图隐藏来自泛型代码的函数调用?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
假设我有一种类似的语言
  1. print "Hello World"

这是透明的

  1. var $__Helpers = {
  2. print: function(s) {
  3. if (typeof s != 'string')
  4. throw new TypeError('String expected');
  5. console.log(s);
  6. }
  7. };
  8.  
  9. $__Helpers.print("Hello World");

如果这种语言的用户

  1. print 5

TypeError将由$__ He​​lpers.print抛出,表示“String expected”.我希望开发人员工具显示打印5行作为此错误的始发调用.我知道如何让我的源地图显示一个看起来像一个调用

  1. transpiled_script.js:2
  2. original_script.os:1

其中transpiled_script.js:2是调用$__ He​​lpers.print函数和original_script.os的脚本和行号:1是要打印的调用的脚本和行号5.我想让开发工具忽略最顶层调用transpiled_script.js(这只是我的transpiler的一个实现细节),并且只显示原始脚本的调用(这是它们在自己的脚本中调试的部分).

我显然不能简单地将transpiled_script.js:2映射到original_script.os:1,因为可以在original_script.os中打印多个调用,因此它不是1到1的关系.

有没有办法做到这一点?

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

解决方法

您可以拆分跟踪并打印所需的行
  1. var $__Helpers = {
  2. print: function(s) {
  3. if (typeof s != 'string'){
  4. var err = new TypeError('String expected');
  5. var trace = err.stack.split('\n')
  6. console.error(trace[0]); // TypeError: string expected
  7. console.error(trace[2]); // the line who called the function,probably
  8. //original_script.os:1,or whatever line number the call was from
  9. //quit the script
  10.  
  11. }
  12. console.log(s);
  13. } };

编辑:一个更好的解决方案,就是替代跟踪的错误,比扔它,代码现在看起来像这样:

  1. var $__Helpers = {
  2. print: function(s) {
  3. if (typeof s != 'string'){
  4. var err = new TypeError('String expected: Got'+s);
  5. err.stack = err.stack.replace(/\n.*transpiled_script\.js.*?\n/g,"\n");
  6. throw err;
  7.  
  8. }
  9. console.log(s);
  10. } };

这也将用于嵌套调用中的错误.

猜你在找的JavaScript相关文章