This article will summarize and share with you some VSCode advanced debugging and usage skills for each scenario, so as to double the efficiency of your daily development work. I hope it will be helpful to everyone!
#VsCode has quickly become popular with its excellent features since its birth. Especially for front-end development partners, it has almost become an indispensable development tool. Therefore, mastering the respective usage skills and debugging skills of VsCode will double the efficiency of your daily development work. This article will use a large number of pictures and texts to introduce various techniques of VsCode in detail from the following aspects:
After VsCode is installed, environment variables will be automatically written , enter code
in the terminal to invoke the VsCode application.
ctrl p
Quickly search for files and jump, add :
to jump to the specified linectrl shift p
Access all available commands based on your current context.
ctrl shift c
Open a terminal externally and navigate to the current project path
ctrl Press the left of key 1 Symbol
Show hidden terminal panel
Ctrl B
Switch sidebar
Ctrl \
Quickly split file editing
alt single left click
Add multiple cursors
alt shift single Left click
Add cursor to all positions in the same column
alt shift mouse selection
Select the area with the same start and end
alt up key or down key
Move the current line or selected area up/down one lineAdd the following configuration in the configuration file to increase the number of characters. Ruler auxiliary lines
"editor.rulers": [40, 80, 100]
The following takes quickly debugging a Node project in VsCode as an example to demonstrate the basic use of breakpoints. The following article will continue to complete various advanced breakpoints.
program
field is used to specify your program entry file, ${workspaceFolder}
represents the current project root path
F5
to start debugging. If debugging is successful, there will be a floating window operation bar. The operation button functions of the floating window are in sequence. For:
F5
), F10
), F11
), Shift F11
), Ctrl Shift F5
) , Shift F5
)Log breakpoint is a variant of ordinary breakpoint. The difference is that will not interrupt debugging , but can log information to the console. Log breakpoints are particularly useful when debugging services that cannot be paused or stopped. Proceed as follows:
You can use {}
to use variables, for example Add a log breakpoint here, the value of b is ${b}
F5
Run to view debugging resultsConditional breakpoint is when the expression result is true
Breakpoints will be made, the steps are as follows:
F5
to debug, the condition is established, so the breakpoint is hit to debug, as shown in the picture, it will interrupt when the index is 9
开发 Web 程序通常需要在 Web 浏览器中打开特定 URL,以便在调试器中访问服务器代码。VS Code 有一个内置功能“ serverReadyAction ”来自动化这个任务。
var express = require('express'); var app = express(); app.get('/', function(req, res) { res.send('Hello World!'); }); app.listen(3000, function() { console.log('Example app listening on port 3000!'); });
{ "type": "node", "request": "launch", "name": "Launch Program", "program": "${workspaceFolder}/app.js", "serverReadyAction": { "pattern": "listening on port ([0-9]+)", "uriFormat": "http://localhost:%s", "action": "openExternally" } }
pattern
是设置匹配的程度端口号,端口号放在小括号内,即作为一个正则的捕获组使用。uriFormat
映射为URI,其中%s
使用pattern
中的第一个捕获组替换。最后使用该URI作为外部程序打开的URI。
F5
调试,会自动打开浏览器,且会在下图所示处中断,当继续执行后,浏览器才能看到输出了server的内容关于NodeJs项目的调试方法,已经在上述的断点的基本使用部分做了介绍,可以网上滚动翻阅。
调试TS项目前,先创建一个TS项目
tsconfig.json
文件# 终端运行 tsc --init
tsconfig.json
文件,开启sourceMap选项和指定编译后输出的路径VS Code 内置了对 Ts 调试的支持。为了支持调试 Ts 与正在执行的 Js 代码相结合,VS Code 依赖于调试器的source map在 Ts 源代码和正在运行的 Js 之间进行映射,所以需要需要开启sourceMap
选项。
{ "sourceMap": true, "outDir": "./out" }
const num: number = 123; console.log(num); function fn(arg: string): void { console.log('fn', arg); } fn("Hello");
手动编译调试TS
在上述的ts基本项目中:
tsc
index.js
和一个index.js.map
文件F5
或者运行 -> 启动调试
,此时可以看到可以正常debug调试通过构建任务构建调试TS
Ctrl+Shift+B
或选择终端 -> 运行生成任务
,此时会弹出一个下拉菜单tsc构建选项
,此时可以看到自动生成了编译文件注意,如果你使用的是其他终端(比如cmder
)的话,有可能会生成不了,如下图所示,使用默认的powershell即可:
F5
即可监视改变并实时编译
Ctrl + Shift + B
选择监视选项,可以实时监视文件内容发生变化,重新编译终端 -> 配置任务 -> 选择任务
可以生成对应的tasks.json配置终端 -> 运行生成任务 -> 点击设置图标
也可以生成对应的tasks.json配置{ "version": "2.0.0", "tasks": [ { "type": "typescript", "tsconfig": "tsconfig.json", "problemMatcher": [ "$tsc" ], "group": "build", "label": "tsc: 构建 - tsconfig.json" } ] }
运行 -> 添加配置 -> 选择nodejs
launch.json
文件中,添加preLaunchTask
字段,值是tasks.json
的label
值,一定要相同,注意大小写。该字段的作用是在执行命令前先执行改task
任务。注意,如果编译后的js文件不在相应的位置,通过图中的outFiles
字段可以指定ts
编译后的js
路径。
index.ts
文件中按F5
启动调试,可以看到调试前已经生成了编译文件,而后就可以正常调试了。vscode本身内置了对ts的支持
vscode内置的ts版本(即工作区版本),仅仅用于IntelliSense(代码提示),工作区ts版本与用于编译的ts版本无任何关系。
修改工作区ts版本的方法:
学会了上述ts的调试后,我们尝试调试html文件,并且html文件中引入ts文件:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <h3>Hello</h3> <script src="./out/index.js"></script> </body> </html>
const num: number = 1221; console.log(num); function fn(arg: string): void { console.log('fn', arg); } document.body.append('World') fn("he");
{ // 使用 IntelliSense 了解相关属性。 // 悬停以查看现有属性的描述。 // 欲了解更多信息,请访问: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ { "type": "pwa-chrome", "request": "launch", "name": "Launch Chrome", "url": "file:///E:/demo/vscode/debug/ts/index.html", "preLaunchTask": "tsc: 构建 - tsconfig.json", "webRoot": "${workspaceFolder}" } ] }
F5
可以正常唤起chrome浏览器,并在vscode的ts源码处会有debug效果下面介绍两种调试vue2项目的3种方法,其他框架的调试也类似:
vue.config.js
,指定要生成sourceMaps资源module.exports = { configureWebpack: { // 生成sourceMaps devtool: "source-map" } };
./vscode/launch.json文件
或者选择运行 -> 添加配置 -> Chrome
{ "version": "0.2.0", "configurations": [ { "type": "chrome", "request": "launch", "name": "vuejs: chrome", "url": "http://localhost:8080", "webRoot": "${workspaceFolder}", "breakOnLoad": true, "pathMapping": { "/_karma_webpack_": "${workspaceFolder}" }, "sourceMapPathOverrides": { "webpack:/*": "${webRoot}/*", "/./*": "${webRoot}/*", "/src/*": "${webRoot}/*", "/*": "*", "/./~/*": "${webRoot}/node_modules/*" }, "preLaunchTask": "serve" } ] }
{ "version": "2.0.0", "tasks": [ { "label": "serve", "type": "npm", "script": "serve", "isBackground": true, "problemMatcher": [ { "base": "$tsc-watch", "background": { "activeOnStart": true, "beginsPattern": "Starting development server", "endsPattern": "Compiled successfully" } } ], "group": { "kind": "build", "isDefault": true } } ] }
该脚本的作用是运行npm run serve
编译命令。
F5
启动调试即可注意:此方式的主要点在于launch.json
配置文件中,通过preLaunchTask
字段指定调试前先运行一个任务脚本,preLaunchTask
的值对应tasks.json
文件中的label
值。
更多详细内容,大家可以点击这里的参考文档查阅。
https://github.com/microsoft/vscode-recipes/tree/main/vuejs-cli
vue.config.js
文件配置,指定要生成sourceMaps资源module.exports = { configureWebpack: { // 生成sourceMaps devtool: "source-map" } };
Debugger for Chrome
插件,并确保没有禁用插件tasks.json
任务# 终端执行命令,启动项目 npm run serve
F5
启动调试即可更多详细内容,请点击这里的参考文档查阅。
https://vuejs.org/v2/cookbook/debugging-in-vscode.html
Debugger for Firfox
在Firefox中调试Debugger for Chrome
基本一样,区别在于安装Debugger for Firfox
插件,并在launch.json配置中,增加调试Firefox的配置即可,配置如下{ "version": "0.2.0", "configurations": [ // 省略Chrome的配置... // 下面添加的Firefox的配置 { "type": "firefox", "request": "launch", "reAttach": true, "name": "vuejs: firefox", "url": "http://localhost:8080", "webRoot": "${workspaceFolder}/src", "pathMappings": [{ "url": "webpack:///src/", "path": "${webRoot}/" }] } ] }
Firefox初始启动时不会触发调试,需要刷新一次
Electron很多人都使用过,主要用于开发跨平台的系统桌面应用。那么来看下vue-cli-electron-builder
创建的Electron
项目怎么调试。步骤如下:
vue.config.js
文件配置,增加sourceMaps配置:module.exports = { configureWebpack: { devtool: 'source-map' } }
.vscode/launch.json
{ "version": "0.2.0", "configurations": [ { "name": "Electron: Main", "type": "node", "request": "launch", "protocol": "inspector", "preLaunchTask": "bootstarp-service", "runtimeExecutable": "${workspaceRoot}/node_modules/.bin/electron", "windows": { "runtimeExecutable": "${workspaceRoot}/node_modules/.bin/electron.cmd" }, "args": ["--remote-debugging-port=9223", "./dist_electron"], "outFiles": ["${workspaceFolder}/dist_electron/**/*.js"] }, { "name": "Electron: Renderer", "type": "chrome", "request": "attach", "port": 9223, "urlFilter": "http://localhost:*", "timeout": 0, "webRoot": "${workspaceFolder}/src", "sourceMapPathOverrides": { "webpack:///./src/*": "${webRoot}/*" } }, ], "compounds": [ { "name": "Electron: All", "configurations": ["Electron: Main", "Electron: Renderer"] } ] }
此处配置了两个调试命令: Electron: Main
用于调试主进程,Electron: Renderer
用于调试渲染进程;compounds[].
选项用于定义复合调试选项; configurations
定义的复合命令是并行的; preLaunchTask
用于配置命令执行前先执行的任务脚本,其值对应tasks.json
中的label
字段; preLaunchTask
用在compounds
时,用于定义configurations
复合任务执行前先执行的脚本。
{ // See https://go.microsoft.com/fwlink/?LinkId=733558 // for the documentation about the tasks.json format "version": "2.0.0", "tasks": [ { "label": "bootstarp-service", "type": "process", "command": "./node_modules/.bin/vue-cli-service", "windows": { "command": "./node_modules/.bin/vue-cli-service.cmd", "options": { "env": { "VUE_APP_ENV": "dev", "VUE_APP_TYPE": "local" } } }, "isBackground": true, "args": [ "electron:serve", "--debug" ], "problemMatcher": { "owner": "custom", "pattern": { "regexp": "" }, "background": { "beginsPattern": "Starting development server\\.\\.\\.", "endsPattern": "Not launching electron as debug argument was passed\\." } } } ] }
在主进程相关代码上打上断点,然后启动调试主进程命令就可以调试主进程了
注意,这里的options
参数是根据实际的情况,自定义添加我们运行项目时所需要的参数,比如我这里因为启动项目的npm命令是:
"serve-local:dev": "cross-env VUE_APP_TYPE=local VUE_APP_ENV=dev vue-cli-service electron:serve"
切换到渲染进程的调试选项,在渲染进程的代码处打上断点,点击调试。注意,此时并不会有断点终端,需要ctrl+r
手动刷新软件进程才会看到渲染进程的断点。
同时开启渲染进程和主进程的调试,只需要切换到调试全部的选项即可。注意,此种方式因为compounds[].configurations
配置是并行执行的,并不一定能保证渲染进程调试一定能附加到主进程调试成功(估计是时机问题),有些时候会调试渲染进程不成功。所以,可以采取上面的方式进行调试。
更多调试Electron的内容,可以点击参考文档查阅。 https://nklayman.github.io/vue-cli-plugin-electron-builder/guide/recipes.html#debugging-with-vscode 补充:更进一步: VS调试React app文档(https://medium.com/@auchenberg/live-edit-and-debug-your-react-apps-directly-from-vs-code-without-leaving-the-editor-3da489ed905f) VS调试Next.js文档(https://github.com/microsoft/vscode-recipes/tree/main/Next-js) 更多...(https://code.visualstudio.com/docs/nodejs/debugging-recipes)
@category:"snippets"
文件 -> 首选项 -> 用户片段
新建全局代码片段文件
添加代码片段文件的文件名称,会生成.code-snippets
后缀的文件
定义用户片段
{ "自动补全console.log": { "scope": "javascript,typescript", "prefix": "log", "body": [ "console.log('$1');", "$2" ], "description": "输出console.log('')" } }
关键词 | 类型 | 说明 |
---|---|---|
scope | string | 代码片段生效的作用域,可以是多个语言,比如javascript,typescript 表示在js和ts生效,不加scope 字段表示对所有文件类型生效 |
prefix | `string | string[]` |
body | string[] | 代码片段内容,数组的每一项会是一行 |
description | string | IntelliSense 显示的片段的可选描述 |
n | - | 定义光标的位置,光标根据数字大小按tab依次跳转;注意$0 是特殊值,表示光标退出的位置,是最后的光标位置。 |
log
时效果如下"body": [ "console.log('${1:abc}');" ],
用两个竖线包含多个选择值,|多个选择值直接用逗号隔开|
"body": [ "console.log('${1:abc}');", "${2|aaa,bbb,ccc|}" ],
只需要选择文件 -> 首选项 -> 用户片段 -> 新建xxx文件夹的代码片段
, 新建后会在当前工作区生成.vscode/xxx.code-snippets
文件
vscode内置了对Emmet的支持,无需额外扩展。例如html的Emmet演示如下:
选中或者光标所处的位置,按F2
可以对所有的变量重命名
VsCode扩展插件可以做什么事情?
基于Yeoman
快速开发VsCode插件,步骤如下:
Yeoman
和用于生成模板的插件VS Code Extension Generator
(https://www.npmjs.com/package/generator-code)# 终端运行,主要node版本需要12及以上,node10会安装报错 npm i -g yo generator-code
yo code
创建命令,选择要生成的项目模板。这里演示New extension
F5
生成编译项目,此时会自动打开一个新窗口Ctrl+Shfit+P
,输入Hello World
命令更多关于VSCode的相关知识,请访问:vscode教程!!
The above is the detailed content of [Summary of vomiting blood] Tips on debugging and using VSCode to double your development work efficiency. For more information, please follow other related articles on the PHP Chinese website!