如何将Browserify捆绑包中的堆栈跟踪转换为原始源代码位置?

akn*_*ds1 8 javascript exception-handling exception browserify source-maps

我想在我的JavaScript应用程序中报告未捕获异常的堆栈跟踪,但问题是所包含的JavaScript是Browserify捆绑包.这意味着当我获得异常的堆栈时,它指的是bundle文件中的位置,即使JavaScript包包含源映射!

如何将堆栈中的文件位置转换为原始源文件?我猜它涉及一些源地图的使用?

下面是一个打印异常的堆栈跟踪的示例程序:

的index.html

<script src="/bundle.js"></script>
Run Code Online (Sandbox Code Playgroud)

index.js

window.onerror = (message, url, line, column, error) => {
  console.log(`An exception was caught for URL ${url}, line ${line}:`, error.stack)
}

const thrower = () => {
  throw new Error(`Catch me if you can`)
}

const callingThrower = () => {
  thrower()
}

callingThrower()
Run Code Online (Sandbox Code Playgroud)

生成捆绑包

# The --debug flag enables inline source maps
browserify --debug -o bundle.js index.js
Run Code Online (Sandbox Code Playgroud)

节目输出

An exception was caught for URL http://localhost:8000/bundle.js, line 7: Error: Catch me if you can
    at thrower (http://localhost:8000/bundle.js:7:9)
    at callingThrower (http://localhost:8000/bundle.js:11:3)
    at Object.1 (http://localhost:8000/bundle.js:14:1)
    at s (http://localhost:8000/bundle.js:1:254)
    at e (http://localhost:8000/bundle.js:1:425)
    at http://localhost:8000/bundle.js:1:443
Run Code Online (Sandbox Code Playgroud)

浏览器

我在OS X上测试了Chrome和Firefox.

Pri*_*dya 1

您可以在代码中做的件事是启用源映射

源映射是告诉浏览器翻译转换代码中的行引用和原始代码中的行引用的文件

这是一个很好的链接,可以帮助您了解sourceMaps

在Browserify中启用源映射非常简单。您只需运行

browserify --debug main.js -o bundle.js
Run Code Online (Sandbox Code Playgroud)

--debug告诉您将 sourceMaps 包含中,bundle.js但缺点是会使您的包大小增加两倍

但是,您可以告诉用户使用插件exorcist单独下载此文件,它会将源映射拆分为bundle.js.map

对我来说,我在as中添加browserify 选项gulpfile.jsgruntfile.js

browserify: {
        dist: {
            src: ['src/main.js'],
            dest: 'dist/bundle.js',
            options: {
                debug: true
            }
        }
    },
Run Code Online (Sandbox Code Playgroud)

要启用它或如本线程中提到的,您可以browserifyOptions使用

options: { browserifyOptions : {} }
Run Code Online (Sandbox Code Playgroud)