当前位置:网站首页>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 .
边栏推荐
- [i.mx6ul] u-boot migration (VI) network driver modification lan8720a
- Using qdomdocument to manipulate XML files in QT
- Tell you about mvcc sequel
- yarn : 无法加载文件 C:\Users\xxx\AppData\Roaming\npm\yarn.ps1,因为在此系统上禁止运行脚本
- 使用ShaderGraph制作边缘融合粒子Shader的启示
- AI自己写代码让智能体进化!OpenAI的大模型有“人类思想”那味了
- 把 Oracle 数据库从 Windows 系统迁移到 Linux Oracle Rac 集群环境(2)——将数据库转换为集群模式
- F - Spices(线性基)
- Squid 代理服务器之 ACL 访问控制
- Can automate - 10k, can automate - 20K, do you understand automated testing?
猜你喜欢
![[live review] battle code pioneer phase 7: how third-party application developers contribute to open source](/img/ad/26a302ca724177e37fe123f8b75e4e.png)
[live review] battle code pioneer phase 7: how third-party application developers contribute to open source

left join on和 join on的区别

Detailed explanation of cache (for the postgraduate entrance examination of XD)

Can automate - 10k, can automate - 20K, do you understand automated testing?

Software testing weekly (issue 77): giving up once will breed the habit of giving up, and the problems that could have been solved will become insoluble.

Copilot免费时代结束!学生党和热门开源项目维护者可白嫖

【STL源码剖析】配置器(待补充)

Once beego failed to find bee after passing the go get command Exe's pit

Advanced mathematics | proficient in mean value theorem problem solving routines summary

Is it out of reach to enter Ali as a tester? Here may be the answer you want
随机推荐
Distributed transaction solutions and code implementation
[STL source code analysis] configurator (to be supplemented)
电脑端微信用户图片DAT格式解码为图片(TK版)
李宏毅《机器学习》丨6. Convolutional Neural Network(卷积神经网络)
vim的Dirvish中文文档
Squid 代理服务器之 ACL 访问控制
It is said that Yijia will soon update the product line of TWS earplugs, smart watches and bracelets
目录权限错误导致 Oracle 11g rac 集群数据库无法启动的问题
The Oracle 11g RAC cluster database cannot be started due to directory permission errors
Error log format and precautions
Computing service network: a systematic revolution of multi integration
js正则匹配数字、大小写字母、下划线、中线和点[通俗易懂]
It's 2022, and you still don't know what performance testing is?
Internship: use of SVN
[analysis of STL source code] functions and applications of six STL components (directory)
把 Oracle 数据库从 Windows 系统迁移到 Linux Oracle Rac 集群环境(2)——将数据库转换为集群模式
小米路由R4A千兆版安装breed+OpenWRT教程(全脚本无需硬改)
记一次beego通过go get命令后找不到bee.exe的坑
ACL access control of squid proxy server
Transformers Roberta如何添加tokens