Home > Development Tools > VSCode > Let's talk about how to click on the DOM in VSCode to automatically locate the corresponding line of code?

Let's talk about how to click on the DOM in VSCode to automatically locate the corresponding line of code?

青灯夜游
Release: 2022-06-23 18:47:58
forward
2724 people have browsed it

How to automatically locate the line of code in VSCode by clicking on the DOM in the Vue project? In this article, I will share a plug-in with you and talk about the implementation principle. Come and collect it!

Let's talk about how to click on the DOM in VSCode to automatically locate the corresponding line of code?

Now large-scale Vue projects are basically developed collaboratively by multiple people, and with the iteration of versions, the number of components in the Vue project will increase. If At this time, you are responsible for the development of unfamiliar page functions. Even if you have just joined this project, how can you quickly find the file location of the relevant components in the entire project code? I believe everyone has taken the following methods:

  • [Search class name], search the style class name in the page DOM element in the project file
  • [Find route], find the page component matching the Vue route according to the page link
  • [Find person], find the person who was responsible for developing the page and ask for the corresponding The code path

The above methods can indeed help us find the specific code file path, but they all require manual search, which is not very efficient. Is there any other more efficient way?

The answer is yes. Vue officially provides a vue-devtools plug-in. Using this plug-in, you can automatically open the source code file of the corresponding page component in VSCode. The operation path is as follows:

Lets talk about how to click on the DOM in VSCode to automatically locate the corresponding line of code?

Using the vue-devtools plug-in can greatly improve the efficiency of finding the corresponding page component code, but it 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 second search in the current component source code, and each time you have to select the component first, and then click the open button to open the code file, which is not particularly fast.

In response to this problem, we have developed a lightweight page element code mapping plug-in. Using this plug-in, you can open the corresponding code source file with one click by clicking on the page element, and accurately locate the corresponding code line, without Manual search can greatly improve development efficiency and experience. The actual usage effect is as follows:

Lets talk about how to click on the DOM in VSCode to automatically locate the corresponding line of code?

Implementation principle

The entire plug-in mainly It is divided into 3 functional modules: client, server, and add-code-location. The client sends a specific request to the server. After receiving the request, the server executes the positioning code line command, and the add-code-location module is used for source code. Convert.

Lets talk about how to click on the DOM in VSCode to automatically locate the corresponding line of code?

1. client

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

Lets talk about how to click on the DOM in VSCode to automatically locate the corresponding line of code?

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

The click event of the monitored page element is monitored globally through the event proxy, the click event is bound to the document, and the keyboard and mouse are monitored. Click the combined event to initiate a request to locate the line of code to avoid conflict with the page's native click event.

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

2. server

The server refers to a local server that can monitor specific requests sent by the client. When receiving When executing a request for a positioning command, execute the VSCode open code file command and locate the corresponding line of code.

2.1 webpack devServer

If it is a project built with webpack, webpack's devServer development server has provided a before attribute, which can be used to monitor and send to the development server request.

before: function (app) {
  app.get('/code', function (req, res) {
    if (req.query.filePath) {
      // 执行vscode定位代码行命令
      openCodeFile(req.query.filePath)
      ...
    }
    ...
  })
}
Copy after login

2.2 vite configureServer

If it is a project built with Vite, you can use the Vite plug-in to monitor specific requests on the server side. The Vite plug-in extends the rollup plug-in interface. And some unique hook functions have been added on the original basis, such as the configureServer hook, through which the development server can be configured 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) // 执行vscode定位代码行命令
          ...
        }
        res.end()
      }
      ...
    })
  }
})
Copy after login

2.3 Execute VSCode positioning command

After the server monitors the specific request sent by the client, the next step is to execute the VSCode positioning code line command. In fact, the VSCode editor can be started through the code command, and some command line parameters can be used accordingly, such as:

"code --reuse-window"或"code -r"命令可以打开最后活动窗口的文件或文件夹;"code --goto"或"code -g"命令后面可以拼接具体文件路径和行列号,当使用"code -g file:line:column"命令时可以打开某个文件并定位到具体的行列位置。

利用 VSCode 编辑器的这个特性,我们就能实现自动定位代码行功能,对应的代码路径信息可以从client端发送的请求信息当中获得,再借助node的child_process.exec方法来执行VSCode定位代码行命令。

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}`)
}
Copy after login

另外,为了正常使用 VSCode 的 Code命令,我们需要确保添加VSCode Code命令到环境变量当中。Mac系统用户可以在VSCode界面使用command+shift+p快捷键,然后搜索Code 并选择install 'code' command in path;Windows用户可以找到VSCode安装位置的bin文件夹目录,并将该目录添加到系统环境变量当中。

3、add-code-location

通过前面的介绍,大家应该了解了client端和server端的执行机制,并且在执行定位命令时需要获取到页面元素的代码路径,而具体的代码路径是以属性的方式绑定到了DOM元素上,这时候就需要用到add-code-location模块在编译时转换我们的源码,并给 DOM元素添加对应的代码路径属性。

整个源码转换处理流程如下:

Lets talk about how to click on the DOM in VSCode to automatically locate the corresponding line of code?

3.1 获取文件路径

源码转换过程的第一步是获取代码文件的具体路径,对于webpack打包的项目来说,webpack loader用来处理源码字符串再合适不过,loader的上下文this对象包含一个resourcePath资源文件的路径属性,利用这个属性我们很容易就能获得每个代码文件的具体路径。

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

对于Vite构建的项目来说,源码的转化操作也是通过插件来完成,Vite插件有通用的钩子transform,可用于转换已加载的模块内容,它接收两个参数,code参数代表着源码字符串,id参数是文件的全路径。

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

3.2 计算代码行号

接着在遍历源码文件的过程中,需要处理对应Vue文件template模板中的代码,以“\n”分割template模板部分字符串为数组,通过数组的索引即可精准得到每一行html标签的代码行号。

function codeLineTrack(str, resourcePath) {
  let lineList =  str.split('\n')
  let newList = []
  lineList.forEach((item, index) => {
    newList.push(addLineAttr(item, index + 1, resourcePath)) // 添加位置属性,index+1为具体的代码行号
  })
  return newList.join('\n')
}
Copy after login

3.3 添加位置属性

在获取到代码文件路径和代码行号以后,接下来就是对Vue template模板中分割的每一行标签元素添加最终的位置属性。这里采用的是正则替换的方式来添加位置属性,分别对每一行标签元素先正则匹配出所有元素的开始标签部分,例如

Lets talk about how to click on the DOM in VSCode to automatically locate the corresponding line of code?

function addLineAttr(lineStr, line, resourcePath) {
  let reg = / {
      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
}
Copy after login

Lets talk about how to click on the DOM in VSCode to automatically locate the corresponding line of code?

4、其他处理

4.1 源码相对路径

在给DOM元素添加对应的源码位置属性时,实际上采用的是相对路径,这样可以使得DOM元素上的属性值更加简洁明了。node_modules文件夹通常是在项目的根目录下,而插件是以npm包的形式安装在node_modules路径下,利用node的__dirname变量可以获得当前模块的绝对路径,因此在源码转换过程中就可以获取到项目的根路径,从而就能获得Vue代码文件的相对路径。

let pathBefore = __dirname.substring(0, __dirname.search('node_modules'))
let filePath = filePath.substring(pathBefore.length) // vue代码相对路径
Copy after login

在server端执行代码定位命令时,再将对应的代码相对路径拼接成完整的绝对路径。

4.2 外部引入组件

add-code-location虽然可以对本地的Vue文件进行代码路径信息的添加,但是对于外部引入或解析加载的组件目前是没有办法进行转换的,例如element ui组件,实际上的代码行信息只会添加在element ui组件的最外层。这时候client端在获取点击元素的代码路径时会做一个向上查找的处理,获取其父节点的代码路径,如果还是没有,会继续查找父节点的父节点,直到成功获取代码路径。

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

这样就可以在点击后台element ui搭建的页面元素时,也能成功定位打开对应代码文件。

接入方案

通过前面的介绍,想必大家对页面元素代码映射插件原理有了清晰的了解,接下来就介绍一下在项目中的接入方式。接入方式其实很简单,并且可以选择只在本地开发环境接入,不用担心对我们的生产环境造成影响,放心使用。

1、webpcak构建项目

对于webpack构建的项目来说,首先在构建配置项vue.config.js文件中配置一下devServer和webpack loader,接着在main.js入口文件中初始化插件。

// vue.config.js
const openCodeServe = require('@vivo/vue-dev-code-link/server')
devServer: {
  ...
  before: openCodeServe.before
},
 
if (!isProd) { // 本地开发环境
  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.js
import openCodeClient from '@vivo/vue-dev-code-link/client'
if (process.env.NODE_ENV == 'development') {
  openCodeClient.init()
}
Copy after login

2、Vite构建项目

Vite构建项目接入该插件的方案和webpack构建项目基本上一致,唯一不一样的地方在于打包配置文件里引入的是两个Vite插件。

// vite.config.js
import 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()
  ]
}
Copy after login

总结

以上就是对页面元素代码映射插件核心原理和接入方案的介绍,实现的方式充分利用了项目代码打包构建的流程,实际上无论是哪个打包工具,本质上都是对源码文件的转换处理,当我们理解了打包工具的运行机制后,就可以做一些自己认为有意义的事。就拿页面元素代码映射插件来说,使用它可以极大提升开发效率,不再需要花费时间在寻找代码文件上,特别是页面数和组件数比较多的项目,只需点击页面元素,即可一键打开对应代码文件,精准定位具体代码行,无需查找,哪里不会点哪里,so easy!

更多关于VSCode的相关知识,请访问:vscode教程

The above is the detailed content of Let's talk about how to click on the DOM in VSCode to automatically locate the corresponding line of code?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:juejin.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template