I have a file that has been transpiled from ES6 to ES5 using Babel. I have sourcemap. I am assuming I can restore the original file (the way it looked when written in ES6) using these resources.
How is it done?
Is there a CLI tool to do this?
To enable source maps in Google Chrome, go to Developer Tools, click the little cog icon, and then make sure that “Enable Javascript source maps” is checked. That's it.
A source map is a file that maps from the transformed source to the original source, enabling the browser to reconstruct the original source and present the reconstructed original in the debugger.
In a sense, source maps are the decoder ring to your secret (minified) code. Using Webpack, specifying devtool: "source-map" in your Webpack config will enable source maps, and Webpack will output a sourceMappingURL directive in your final, minified file.
Source maps connect the bundle file with corresponding source files. Source maps are not a Webpack only concept. It is a common debugging technique which is respected by all modern browsers. Webpack has the ability to generate source maps.
Open up the source map in a text editor, and you’ll see that it’s mostly just a simple JSON object. The “sources” field contains an array of URLs/paths to all source files, which can help you to find them. There is also an optional “sourcesContent” field, which also is an array, where each item contains the contents of the file at the same index in the “sources” array; if so, you could find the original code right in the source map.
A CLI tool? Well, there’s source-map-visualize which tries to find all original sources and pre-loads them into this online source map visualization.
Very simple NodeJS implementation which I wrote for my needs.
const fs = require('fs');
const { SourceMapConsumer } = require("source-map");
fs.readFile('./example.js', 'utf8' , (err, data) => {
if (err) return console.error(err);
const sourceMapData = data.split('//# sourceMappingURL=data:application/json;base64,')[1];
let buff = new Buffer.from(sourceMapData, 'base64');
let rawSourceMap = buff.toString('ascii');
const parsed = SourceMapConsumer(rawSourceMap);
fs.writeFile('example.ts', parsed.sourcesContent, function (err) {
if (err) return console.log(err);
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With