preface

This article documents the use of the Mozilla/source-Map library to locate errors in packaged JS code. The principle of sourcemap files is not covered here. There are many excellent tutorial articles on the web. For example, ruan Yifeng teacher’s JavaScript Source Map details and JoeyGuo’s script error volume optimization – make the script error at a glance.

Let’s deepen our understanding of sourceMap in practice in this article. (It is recommended to read the above two articles before starting to practice)

The process is very simple as follows:

  1. Prepare demo and generate sourceMap
  2. Use mozilla/ source-Map library processing to identify the error source file, the number of lines and columns of the error source file, and the original variable name

All demos are located at the following GitHub address: Joeoeoe/source-map-demo

Prepare demo and generate sourceMap

To configure a simple Webpack:

//webpack.config.js
const path = require("path");

module.exports = {
  devtool: "source-map".entry: "./src/index.js".output: {
    filename: "main.js".path: path.resolve(__dirname, "dist"),}};Copy the code

Create index.js and moudleb.js in the SRC folder

// moduleA.js
const moudleA = "moduleA";

module.exports = moudleA;
Copy the code
// index.js
const moudleA = require("./moduleA");
console.log(moudleA);

if (true) {
  console.log(a); // Simulation error
}
Copy the code

Next, we use webpack, because our webpack is configured with devtool: “source-map”, so main.js and main.js.map will be generated.

// main.js, a string of compressed code with the end pointing to the corresponding sourceMap
!function(e){var t={};function n(r){if(t[r])return t[r].exports;var o=t[r]={i:r,l:!1.exports: {}}; .//# sourceMappingURL=main.js.map
Copy the code
// main.js.map sourceMap content, let's format it to see
{"version":3."sources": ["webpack:///webpack/bootstrap"."webpack:///./src/moduleA.js"."webpack:///./src/index.js"]...Copy the code

Using the JSON formatting tool, look at the contents of sourceMap:

Below the Sources array is the pre-conversion file whose contents correspond to the sourcesContent subscript. By looking at sourcesContent, you can see that Webpack/Bootstrap is webPack’s browser-side emulation of require. Other attributes are explained in detail in teacher Ruan yifeng’s article, which will not be repeated here.

Now that demo is ready, you can locate errors based on sourceMap.

usingMozilla/source – the map libraryPositioning error

The common solution for using sourceMap to locate errors in a project is as follows (figure fromScript error volume optimization – make the script error at a glance) :

**//# sourceMappingURL=main.js.map** in main.js, add error listener in dist/index.html:

    <script>
      window.onerror = function (msg, url, row, col, error) {
        const obj = {
          msg,
          url,
          row,
          col,
        };
        console.log(obj);
      };
    </script>
Copy the code

Open the HTML to see:

With row and col in place, use the Mozilla /source-map library to get the error location in the source file.

NPM source – the map I installed the source – the map library, under the project of new trySourceMap. Js file:

const fs = require("fs");
const sourceMap = require("source-map"); / / mozilla/source - the map library
const rawSourceMap = JSON.parse(
  // The sourceMap file is packaged
  fs.readFileSync("./dist/main.js.map").toString()
);

const errorPos = {
  // The wrong location in the figure above
  line: 1.column: 946};async function main() {
  const consumer = await new sourceMap.SourceMapConsumer(rawSourceMap); // Get sourceMap Consumer, where we can query the source code location by passing in the packaged code location

  const originalPosition = consumer.originalPositionFor({ // Get the source of the error code and its location
    line: errorPos.line,
    column: errorPos.column,
  });
  // { source: 'webpack:///src/index.js', line: 4, column: 14, name: 'a' }

  // Find the corresponding source file based on the source file name
  const sourceIndex = consumer.sources.findIndex(
    (item) = > item === originalPosition.source
  );
  const sourceContent = consumer.sourcesContent[sourceIndex];
  const contentRowArr = sourceContent.split("\n"); / / shard
  / / /
  //  'const moudleA = require("./moduleA");\r',
  // '\r',
  // 'if (true) {\r',
  // ' console.log(a); \r',
  // '}\r',
  / /"
  // ]

  // Next you can get more specific positions based on rows and columns
  console.log(contentRowArr[originalPosition.line - 1]);

  consumer.destroy(); // Remember destroy after use
}

main();
Copy the code

This captures the location of the error code in the source file.

conclusion

Source map-demo: Joeoeoe: sourceMap: sourceMap: sourceMap: sourceMap: sourceMap: sourceMap

The resources

Mozilla/Source-map — Github How does WebPack achieve front-end modularity