diff --git a/README.md b/README.md index 035a101..19833a5 100644 --- a/README.md +++ b/README.md @@ -8,11 +8,16 @@ This module provides source map support for stack traces in node via the [V8 sta npm install source-map-support -Source maps can be generated using libraries such as [source-map-index-generator](https://github.com/twolfson/source-map-index-generator). Once you have a valid source map, insert the following two lines at the top of your compiled code: +Source maps can be generated using libraries such as [source-map-index-generator](https://github.com/twolfson/source-map-index-generator). Once you have a valid source map, insert the following line at the top of your compiled code: - //# sourceMappingURL=path/to/source.map require('source-map-support').install(); +And place a source mapping comment somewhere in the file (usually done automatically or with an option by your transpiler): + + //# sourceMappingURL=path/to/source.map + +If multiple sourceMappingURL comments exist in one file, the last sourceMappingURL comment will be +respected (e.g. if a file mentions the comment in code, or went through multiple transpilers). The path should either be absolute or relative to the compiled file. It is also possible to to install the source map support directly by @@ -81,10 +86,11 @@ original.js: compiled.js: - //# sourceMappingURL=compiled.js.map require('source-map-support').install(); throw new Error('test'); // This is the compiled code + // The next line defines the sourceMapping. + //# sourceMappingURL=compiled.js.map compiled.js.map: diff --git a/source-map-support.js b/source-map-support.js index 6d9f4c5..ab191a8 100644 --- a/source-map-support.js +++ b/source-map-support.js @@ -72,9 +72,13 @@ function retrieveSourceMapURL(source) { // Get the URL of the source map fileData = retrieveFile(source); - var match = /\/\/[#@]\s*sourceMappingURL=([^'"]+)\s*$/m.exec(fileData); - if (!match) return null; - return match[1]; + var re = /\/\/[#@]\s*sourceMappingURL=([^'"]+)\s*$/mg; + // Keep executing the search to find the *last* sourceMappingURL to avoid + // picking up sourceMappingURLs from comments, strings, etc. + var lastMatch, match; + while (match = re.exec(fileData)) lastMatch = match; + if (!lastMatch) return null; + return lastMatch[1]; }; // Can be overridden by the retrieveSourceMap option to install. Takes a diff --git a/test.js b/test.js index f2bf344..67794fa 100644 --- a/test.js +++ b/test.js @@ -250,6 +250,16 @@ it('sourcesContent with data URL', function() { ]); }); +it('finds the last sourceMappingURL', function() { + compareStackTrace(createMultiLineSourceMapWithSourcesContent(), [ + '//# sourceMappingURL=missing.map.js', // NB: compareStackTrace adds another source mapping. + 'throw new Error("test");' + ], [ + 'Error: test', + /^ at Object\.exports\.test \(.*\/original.js:1002:5\)$/ + ]); +}); + it('default options', function(done) { compareStdout(done, createSingleLineSourceMap(), [ '',