Badass JavaScript

A showcase of awesome JavaScript that pushes the boundaries of what's possible on the web, by @devongovett.

Node.js Source Map Support for Better Compiled JavaScript Debugging

February 8th 2013

Evan Wallace, who’s work I’ve covered several times before has been working on a module to add source map support to Node.js.  Source maps will be really important for debugging compiled to JavaScript languages like CoffeeScript, as well as for debugging minified or concatenated production JavaScript.

As their name implies, source maps provide a mapping from the compiled code the browser is running to the original source files.  This way, when errors occur, the stack traces can display the correct line and column numbers from the original source.  They can go even further than that, giving correct information in profilers, consoles, and more.  You can find a good tutorial about source maps over on HTML5 Rocks.  So far, they have been implemented in the Chrome Dev Tools, and Firefox is working on getting them implemented as well.  As for compiler support, the main CoffeeScript compiler still lacks support for source map generation, but the CoffeeScriptRedux compiler has support.  Microsoft’s TypeScript language also has support, and both Google Closure Compiler and UglifyJS2 can generate source maps for minified JavaScript as well.

As for Node.js support, there isn’t any built in.  The Node core developers aren’t really big fans of compile to JavaScript languages as far as I can tell.  There is an open bug on the Node Github project to add support, but it’s 7 months old and hasn’t gotten much traction.  Luckily, it doesn’t have to be in Node core to work, and so Evan Wallace wrote this module to add support in user land.

To use it, you just require the source-map-support module from npm, and like magic all of your stack traces will now contain correct line numbers.  It uses V8’s handy Stack Trace API to capture errors and rewrite their stack traces just before they are thrown and printed out if not caught.  It also uses Mozilla’s source-map module to do the actual source map parsing and mapping.  That module can also be used for source map generation, and CoffeeScriptRedux does just that.

Anyway, if you have been itching for source map support in Node.js like I have, go check out source-map-support on Github and npm, and start debugging better.  Source maps can solve 90% of the issues people have had with compile to JS languages, so I’m glad to see them arriving in both the browser as well as Node.js.