Friday, May 22, 2020

Source Map

Source Map helps us debug JavaScript code in production. Source Map creates a mapping between the original development version of the JavaScript / JSX files and the compiled and bundles production version of the JavaScript files, thereby allowing us to debug in production.

In the previous posts we saw how Bable compiles the ES6 & JSX code and transforms them into JavaScript and how webpack bundles the individual files into a common bundle.js file. As a result of the transpilation, minification and bundling process we are left with a large JavaScript file which is almost impossible to debug, but we cannot avoid these steps since they are required to make the JavaScript application secure and performance efficient in the production environment. If so then how do we debug issues in production environment, the answer to this is Source Map.

SourceMap is a JSON which contains all mapping details between the original JavaScript / JSX code and the bundled JavaScript. SourceMap contains details like path of original file, details of the bundled file. The browser downloads the source map file and uses it to map to the original version of the code when in Development mode.

In our HelloWorld React application we did not enable Source Map, just run the application and open the browser console, you will find a large bundle.js file as follows. The bundle.js file contains our application code along with dependent package code, in the very simple Hello World application the bundle.js file had 603 lines of code.


Now let us enable Source Map in the web-pack config file by adding the below setting.

module.exports = {
  devtool: 'inline-source-map',
  . . .
};

Build and run the application, now notice that the index.js file is available in the /src folder, also we are able to set a break point and debug the React component class as follows.




Before adding the source map setting to the web-pack config file, the index.js file was like this.


Search Flipkart Products:
Flipkart.com

No comments: