Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use JavaScript source maps (.map files)?

Recently I have seen files with the .js.map extension shipped with some JavaScript libraries (like Angular), and that just raised a few questions in my head:

  • What is it for? Why do the guys at Angular care to deliver a .js.map file?
  • How can I (as a JavaScript developer) use the angular.min.js.map file?
  • Should I care about creating .js.map files for my JavaScript applications?
  • How does it get created? I took a look at angular.min.js.map and it was filled with strange-formatted strings, so I assume it's not created manually.
like image 567
Muhammad Reda Avatar asked Feb 12 '14 05:02

Muhammad Reda


2 Answers

The .map files are for JavaScript and CSS (and now TypeScript too) files that have been minified. They are called source maps. When you minify a file, like the angular.js file, it takes thousands of lines of pretty code and turns it into only a few lines of ugly code. Hopefully, when you are shipping your code to production, you are using the minified code instead of the full, unminified version. When your app is in production, and has an error, the source map will help take your ugly file, and will allow you to see the original version of the code. If you didn't have the source map, then any error would seem cryptic at best.

Same for CSS files. Once you take a Sass or Less file and compile it to CSS, it looks nothing like its original form. If you enable sourcemaps, then you can see the original state of the file, instead of the modified state.

So, to answer you questions in order:

  • What is it for? To de-reference uglified code
  • How can a developer use it? You use it for debugging a production app. In development mode you can use the full version of Angular. In production, you would use the minified version.
  • Should I care about creating a js.map file? If you care about being able to debug production code easier, then yes, you should do it.
  • How does it get created? It is created at build time. There are build tools that can build your .map file for you as it does other files. Sourcemaps fail if the output file is not located in the project root directory #71

I hope this makes sense.

like image 189
frosty Avatar answered Sep 28 '22 05:09

frosty


How can a developer use it?

  1. Don't link your js.map file in your index.html file (no need for that)

  2. Minification tools (good ones) add a comment to your .min.js file:

    //# sourceMappingURL=yourFileName.min.js.map 

    which will connect your .map file.

    When the min.js and js.map files are ready...

  3. Chrome: Open dev-tools, navigate to Sources tab. You will see the sources folder, where un-minified applications files are kept.

like image 31
garfunkel61 Avatar answered Sep 28 '22 05:09

garfunkel61