How to implement a tracking log output location plugin?

FreeCoderX - Feb 22 '22 - - Dev Community

Summary content

  • Environment construction
  • Implementation steps
  • Summarize

Achieve the effect

Often we console.log to print the log. If the editor does not support it well, then the print log does not know which file and which line is printed, so we need to know which file and which line the log is printed in, and finally achieve the effect As shown below

Image description

Environment setup

  • Initialize project npm init -y
  • Install dependencies npm install @babel/core @babel/preset-env @babel/types babel-loader webpack webpack-cli -D
  • Create directories and pack files

Image description

Image description

  • configure webpack.config.js

Image description

Analyze the AST of the code

Look at console.log(“sum: sdf”); what it looks like when converted to AST. In order to see more clearly, we check all the buttons above to make AST look simpler and clearer

Image description

Console output log format

  • Case 1: console.log(“sum: sdf”);

Image description

  • Case 2: console.log(“sum: sdf”,”123");

Image description

  • Case 3: console.log(“123”,”sum: sdf” + “sdf”);

Image description

Adjust the AST syntax tree

According to the AST structure of various output console formats, compare and see how to adjust the AST

According to the above AST analysis, we have the idea of ​​​​implementing, which is not to find the log method in the console, and then add a parameter at the end of the argument to spell the log output source code file and output function.

Implement the plugin

Summarize

  • Check the AST structure first, and then compare the AST structure to get AST adjustment ideas
  • Combining debugging + official documentation to achieve functional details Source code portal: 04-traceLogPos

References

Above: If you find any problems, please leave a message and point it out, and I will correct it in time

Thanks for reading, welcome to follow me for more technical articles

. . . . . .