当前位置:网站首页>How to click DOM to automatically locate the corresponding code line in vscode

How to click DOM to automatically locate the corresponding code line in vscode

2022-06-25 02:51:00 Yisu cloud

VSCode How to realize clicking in DOM Automatically navigate to the appropriate line of code

This article introduces in detail “VSCode How to realize clicking in DOM Automatically navigate to the appropriate line of code ”, Detailed content , The steps are clear , The details are handled properly , Hope this article “VSCode How to realize clicking in DOM Automatically navigate to the appropriate line of code ” The article can help you solve your doubts , Let's follow Xiaobian's ideas and go deeper slowly , Let's learn new knowledge together .

Now the large Vue Projects are basically developed by multiple people , And as the versions iterate ,Vue There will be more and more components in the project , If you are responsible for the development of unfamiliar page functions , Even if you just joined the project , So how to quickly find the file location of related components in the whole project code ? We must have adopted the following methods :

  • 【 Search class name 】, Search the page in the project file DOM The style class name in the element

  • 【 Find a route 】, Find... According to the page link Vue Route matching page components

  • 【 look for sb. 】, Find the person who was responsible for developing the page and ask for the corresponding code path

The above methods can really help us find the specific code file path , But they all need to be searched manually , It's not very efficient , Is there any other more efficient way ?

The answer is yes .Vue The official has provided one vue-devtools plug-in unit , Using this plug-in, you will be able to automatically VSCode Open the source code file of the corresponding page component in

Use vue-devtools The plug-in can improve the efficiency of finding the corresponding page component code , But you can only locate the corresponding component code , If we want to directly find the specific code location related to an element on the page , You also need to perform a secondary search in the current component source code , And you have to select components first every time , Then click the open button to open the code file , Not particularly fast .

In response to this question , We have developed a lightweight page element code mapping plug-in , Using this plug-in, you can click on the page element , Open the corresponding code source file with one click , And precisely locate the corresponding code line , No need to manually find , It can greatly improve the development efficiency and experience .

Two 、 Realization principle

The whole plug-in is mainly divided into 3 Function modules :client、server、add-code-location,client The client sends a specific request to server End ,server After receiving the request, the client executes the location code line command , and add-code-location Module is used for source code conversion .


2.1 client

client End here actually refers to the browser , When we click on a page element , The browser will send a specific request to server End , The request information contains the specific code file path and the corresponding code line number information .

function openEditor(filePath) {  axios    .get(`${protocol}//${host}:${port}/code`, {      params: {        filePath: `${filePath}`      }    })    .catch(error => {      console.log(error)    })}

The click events of page elements are monitored globally through the event agent , to document Bound click event , Listen for keyboard and mouse click combination events to initiate location code line requests , Avoid being native to the page click The incident clashed .

function openCode(e) {  if (isShiftKey || isMetaKey || e.metaKey || e.shiftKey) {    e.preventDefault()    const filePath = getFilePath(e.target)    openEditor(filePath)  }  ...}

2.2 server

server End refers to a local The server , Can monitor client A specific request sent by the client , When a request to execute a positioning command is received , perform VSCode Open code file command , And navigate to the corresponding code line .

2.2.1 webpack devServer

If you use webpack Projects built ,webpack Of devServer The development server already provides a before attribute , It can be used to listen for requests sent to the development server .

before: function (app) {  app.get('/code', function (req, res) {    if (req.query.filePath) {      //  perform vscode Locate the code line command       openCodeFile(req.query.filePath)      ...    }    ...  })}

2.2.2 vite configureServer

If you use Vite Projects built , have access to Vite Plug in server The client listens for specific requests ,Vite The plug-in extends to rollup Plug-in interface , In addition, some special hook functions are added on the original basis , for example configureServer hook , This hook function can be used to configure the development server to listen for specific requests .

const codeServer = () => ({  name: 'open-code-vite-server',  configureServer(server) {    server.middlewares.use((req, res, next) => {      ...      if (pathname == '/code') {        ...        if (filePath) {          openCodeFile(filePath) //  perform vscode Locate the code line command           ...        }        res.end()      }      ...    })  }})

2.2.3 perform VSCode Locate the command

When server End monitor hearing client After a specific request sent by the client , The next step is to perform VSCode Locate the code line command . actually ,VSCode The editor can be accessed through code Command to start , And you can use some command line arguments accordingly , for example :

"code --reuse-window" or "code -r" Command can open the file or folder of the last active window ;"code --goto" or "code -g" The specific file path and row / column number can be spliced after the command , When using "code -g file:line:column" Command to open a file and navigate to a specific row and column location .

utilize VSCode This feature of the editor , We can implement the function of automatically locating code lines , The corresponding code path information can be obtained from client From the request information sent by the client , Again with the help of node Of child_process.exec Method to execute VSCode Locate the code line command .

const child_process = require('child_process')function openCodeFile(path) {  let pathBefore = __dirname.substring(0, __dirname.search('node_modules'))  let filePath = pathBefore + path  child_process.exec(`code -r -g ${filePath}`)}

in addition , For normal use VSCode Of Code command , We need to make sure we add VSCode Code Command to environment variable .Mac The system user can VSCode Interface to use command+shift+p Shortcut key , And then the search Code And select install 'code' command in path;Windows Users can find VSCode The installation position is bin Folder Directory , And add the directory to the system environment variable .

2.3 add-code-location

Through the previous introduction , You should understand client End sum server The execution mechanism of the end , And when executing the positioning command, you need to get the code path to the page element , The specific code path is bound to... In the form of attributes DOM Element , And that's where it comes in add-code-location The module converts our source code at compile time , And give DOM Element to add the corresponding code path attribute .

2.3.1 Get file path

The first step in the source code conversion process is to obtain the specific path of the code file , about webpack For packaged projects ,webpack loader It is suitable to handle the source string ,loader The context of this Object contains a resourcePath The path attribute of the resource file , Using this property, we can easily get the specific path of each code file .

module.exports = function (source) {  const { resourcePath } = this  return sourceCodeChange(source, resourcePath)}

about Vite To build a project , The conversion of source code is also completed through plug-ins ,Vite The plug-in has a universal hook transform, It can be used to convert the loaded module content , It takes two parameters ,code The parameter represents the source code string ,id The parameter is the full path of the file .

module.exports = function() {  return {    name: 'add-code-location',    transform(code, id) {      ...      return sourceCodeChange(code, id)    }  }}

2.3.2 Calculate code line numbers

Then in the process of traversing the source file , You need to deal with the corresponding Vue file template The code in the template , With “\n” Division template The string of the template part is an array , Through the index of the array, each row can be accurately obtained html Code line number of the tag .

function codeLineTrack(str, resourcePath) {  let lineList =  str.split('\n')  let newList = []  lineList.forEach((item, index) => {    newList.push(addLineAttr(item, index + 1, resourcePath)) //  Add location attribute ,index+1 For specific code line numbers   })  return newList.join('\n')}

2.3.3 Add location attribute

After getting the code file path and code line number , The next thing is right Vue template The final position attribute is added to each row of label elements divided in the template . Here we use the regular replacement method to add the location attribute , For each line of label elements, the start label part of all elements shall be regularly matched , for example <div、<span、<img etc. , Then replace it with a regular with code-location The start tag of the attribute , The corresponding attribute value is the code path and the line number of the corresponding tag .

function addLineAttr(lineStr, line, resourcePath) {  let reg = /<[\w-]+/g  let leftTagList = lineStr.match(reg)  if (leftTagList) {    leftTagList = Array.from(new Set(leftTagList))    leftTagList.forEach(item => {      if (item && item.indexOf('template') == -1) {        let regx = new RegExp(`${item}`, 'g')        let location = `${item} code-location="${resourcePath}:${line}"`        lineStr = lineStr.replace(regx, location)      }    })  }  return lineStr}

2.4 Other treatments

2.4.1 Source relative path

In giving DOM Element to add the corresponding source location attribute , In fact, the relative path is adopted , This will allow DOM The attribute values on the element are more concise .node_modules The folder is usually in the root directory of the project , The plug-in is based on npm The package is installed in node_modules Under the path , utilize node Of __dirname Variable can obtain the absolute path of the current module , Therefore, the root path of the project can be obtained in the process of source code transformation , So that we can get Vue The relative path of the code file .

let pathBefore = __dirname.substring(0, __dirname.search('node_modules'))let filePath = filePath.substring(pathBefore.length) // vue Code relative path 

stay server When the client executes the code positioning command , Then the relative path of the corresponding code is spliced into a complete absolute path .

2.4.2 External lead-in components

add-code-location Although it can be applied to local Vue File to add code path information , However, there is no way to convert externally imported or parsed loaded components , for example element ui Components , The actual code line information will only be added in element ui The outermost layer of a component . Now client When getting the code path of the clicked element, the client will do an upward search , Get the code path of its parent node , If there is still no , Will continue to find the parent node of the parent node , Until the code path is successfully obtained .

function getFilePath(element) {  if (!element || !element.getAttribute) return null  if (element.getAttribute('code-location')) {    return element.getAttribute('code-location')  }  return getFilePath(element.parentNode)}

So you can click on the background element ui When building page elements , You can also successfully locate and open the corresponding code file .

3、 ... and 、 Access plan

Through the previous introduction , You must have a clear understanding of the principle of the page element code mapping plug-in , Next, I will introduce the access methods in the project . The access method is actually very simple , And you can choose to access only in the local development environment , Don't worry about the impact on our production environment , Ease of use .

3.1 webpcak Build the project

about webpack To build a project , First, build the configuration item vue.config.js Configure it in the file devServer and webpack loader, And then main.js Initialize the plug-in in the entry file .

// vue.config.jsconst openCodeServe = require('@vivo/vue-dev-code-link/server')devServer: {  ...  before: openCodeServe.before}, if (!isProd) { //  Local development environment   config.module    .rule('vue')    .test(/\.vue/)    .use('@vivo/vue-dev-code-link/add-location-loader')    .loader('@vivo/vue-dev-code-link/add-location-loader')    .end()}// main.jsimport openCodeClient from '@vivo/vue-dev-code-link/client'if (process.env.NODE_ENV == 'development') {  openCodeClient.init()}

3.2 Vite Build the project

Vite Build the project access scheme and webpack Build projects are basically the same , The only difference is that the packaging configuration file introduces two Vite plug-in unit .

// vite.config.jsimport openCodeServer from '@vivo/vue-dev-code-link/vite/server'import addCodeLocation from '@vivo/vue-dev-code-link/vite/add-location'export default defineConfig({  plugins: [    openCodeServer(),    addCodeLocation()  ]}

Read here , This article “VSCode How to realize clicking in DOM Automatically navigate to the appropriate line of code ” The article has been introduced , If you want to master the knowledge points of this article, you need to practice and use it yourself to understand , If you want to know more about this article , Welcome to the Yisu cloud industry information channel .

原网站

版权声明
本文为[Yisu cloud]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/176/202206242342427529.html