Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I translate stack traces from Browserify bundles to the original source code positions?

I would like to report stack traces from uncaught exceptions in my JavaScript app, but the problem is that the included JavaScript is a Browserify bundle. This means that when I obtain the stack of an exception, it refers to positions within the bundle file, even if the JavaScript bundle contains source maps!

How can I translate the file positions within the stack to the original source files? I guess it involves some use of source maps?

Below is an example program that prints the stack trace of an exception:

index.html

<script src="/bundle.js"></script>

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()

Generate the Bundle

# The --debug flag enables inline source maps
browserify --debug -o bundle.js index.js

Program Output

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

Browsers

I've tested with Chrome and Firefox on OS X.

like image 434
aknuds1 Avatar asked Dec 06 '16 14:12

aknuds1


1 Answers

One thing you can do in your code is to enable the sourcemaps

The source maps are the files that tell your browser to translate the line references in your transformed code and the line references in your original code.

Here is a good link to get an idea of the sourceMaps

Enabling the source maps is very easy in the Browserify.You just have to run

browserify --debug main.js -o bundle.js

--debug tells you to include the sourceMaps in the bundle.js but to a disadvantage it makes your bundle twice as large

However you can tell the users to download this file separately by using the plugin exorcist and it will split the source maps into bundle.js.map

For me I add the browserify options in the gulpfile.js as gruntfile.js as

browserify: {
        dist: {
            src: ['src/main.js'],
            dest: 'dist/bundle.js',
            options: {
                debug: true
            }
        }
    },

to enable it or as mentioned in this thread you can use browserifyOptions instead as

options: { browserifyOptions : {} }
like image 59
Pritish Vaidya Avatar answered Oct 15 '22 05:10

Pritish Vaidya