Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use sourcemaps to restore the original file?

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?

like image 943
Gajus Avatar asked Sep 03 '15 19:09

Gajus


People also ask

How do I use Sourcemaps in Chrome?

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.

What are Sourcemaps used for?

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.

How do Webpack Sourcemaps work?

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.

What is Sourcemaps in Webpack?

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.


2 Answers

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.

like image 185
lydell Avatar answered Sep 21 '22 09:09

lydell


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);
  });
});
like image 22
Dmitri Avatar answered Sep 18 '22 09:09

Dmitri