Since its inception, VsCode has been rapidly gaining popularity due to its unique features. Especially for front-end development partners, almost become an essential development tool. Therefore, mastering VsCode’s respective techniques and debugging skills will make your daily development work more efficient. This article will cover VsCode’s various techniques in graphic detail from the following aspects:

  • The first part mainly introduces the basic skills of VsCode, such as common shortcuts, auxiliary rulers, etc. Those familiar with this section can skip it.
  • The second part focuses on various breakpoints (such as log breakpoints, inline breakpoints, expression breakpoints, and so on), data panels, and so on
  • The third part mainly explains the debugging of various projects, such as Node program, TS program, Vue program, Electron program, Html and so on
  • The final section will cover other useful techniques, such as snippets, refactoring, Emmet, and more

Basic skills

Quick start

After VsCode is installed, environment variables are automatically written, and the terminal can invoke the VsCode application by typing code.

Common Shortcut keys

  • ctrl + pQuick search for files and jump to add:You can jump to the specified row

  • CTRL + Shift + P accesses all available commands based on your current context.

  • CTRL + Shift + C opens the terminal externally and locates the current project path

  • CTRL + 1 The symbol on the left shows the hidden terminal panel

  • Ctrl+B toggles the sidebar

  • Ctrl+\ Fast split file editing

  • Alt + Single left click to add multiple cursors

  • Alt + Shift + Click all positions in the same column to add the cursor

  • Alt + Shift + mouse Select Select the same start and end areas

  • Alt + up or downMoves the current row or selected region up/down one line

Vertical ruler

Add the following configuration to the configuration file to add a character ruler auxiliary line

"editor.rulers": [40.80.100]
Copy the code

Advanced skills

Basic use of breakpoints

The following shows the basic use of breakpoints by quickly debugging a Node project in VsCode. The rest of this article continues to end various advanced breakpoints.

  • Create a basic Node project called Nodejs
  • Open the debug panel on the left, select the Name of the Node project you want to debug, and add the debug configuration

  • Select the project type to debug as Node.js

  • Open the generated.vscode/launch.json file and specify the program entry file

The Program field specifies your program entry file, and ${workspaceFolder} represents the current project root path

  • To add a breakpoint in a program, just click on the left sidebar to add a breakpoint

  • According to theF5Start debugging, successful debugging will have floating window operation bar

The functions of the operation buttons of the floating window are as follows:

  • To continue,F5),
  • Debug next step (F10),
  • Jump into one step (F11),
  • Step out (Shift F11),
  • Redebugging (Ctrl + Shift + F5),
  • End debugging (Shift + F5)

Log breakpoint

A logging breakpoint is a variation of a normal breakpoint, except that debugging is not interrupted and information is logged to the console. Logging breakpoints are particularly useful for debugging services that cannot be paused or stopped. The steps are as follows:

  • Steps to add log breakpoints

  • Enter information about the breakpoint you want to log and press Enter to add it

Variables can be used with {}, such as adding a log breakpoint here, where b has the value ${b}

  • A diamond icon appears after logging breakpoints are added successfully

  • According to theF5Run to view the debugging result

Expression conditional breakpoint

Conditional breakpoints are broken only when the expression result is true, as follows:

  • You can also add a breakpoint by right – clicking on the left side of the line

  • Fill in the expression and press Enter

  • The following ICONS are successfully added

  • According to theF5Debug, the condition is set so a breakpoint

Hit count breakpoint

A breakpoint occurs only if the line hits a specified number of times. The steps are as follows:

  • Select a conditional breakpoint, switch to hit count, and enter hit count

  • Fill in successfully, as shown in the following figure

  • According to theF5Debugging, as shown in the figure, is interrupted only when index is 9

Inline breakpoint

Inline breakpoints are hit only if the execution reaches the column associated with the inline breakpoint. This is especially useful when debugging miniaturized code that contains multiple statements in a single line. This is especially useful when a single line of code contains multiple expressions, such as a for loop or short-circuit operator. The steps are as follows:

  • Press at the specified positionShift + F9

  • After debugging, every time the code runs to that inline is broken

Supplementary knowledge point: data panel introduction

  • All variables can be viewed in the data panel

  • Right click on a variable, you can set the value of the variable, copy the value of the variable and other operations

  • When you focus on the data panel, you can search and filter by typing values. Click the button shown below to control whether to filter.

Supplementary knowledge: monitor panel introduction

You can add variables to the listener panel and watch them change in real time.

  • Add variables to the listener panel by right-clicking “Add to Monitor” in the variables panel

  • You can also add variables directly by selecting the Add button in the listener panel

  • After adding variables, you can listen for changes in real time

Open a URI when debugging the server

Developing a Web program often requires opening a specific URL in a Web browser to access the server code in a debugger. VS Code has a built-in feature “serverReadyAction” to automate this task.

  • A simple piece of server code
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! ');
});
Copy the code
  • Configure launch.json to support opening the URI
{
  "type": "node"."request": "launch"."name": "Launch Program"."program": "${workspaceFolder}/app.js"."serverReadyAction": {
    "pattern": "listening on port ([0-9]+)"."uriFormat": "http://localhost:%s"."action": "openExternally"}}Copy the code

Pattern is the port number that sets the degree of matching. The port number is enclosed in parentheses and is used as a regular capture group. UriFormat maps to URI, where %s uses the first capture group substitution in pattern. Finally, this URI is used as the URI to open the external program.

  • According to theF5Debugging, the browser will automatically open, and will be interrupted as shown in the following figure, when the execution continues, the browser can see the output of the server content

Endgame: each scene debugging actual combat

Debug the NodeJS project

Debugging methods for the NodeJs project are described in the basic usage of breakpoints section above, which you can scroll through online.

Debug Typescript projects

  • Before debugging the TS project, create a TS project

    • Initialize a TS program to generate the defaulttsconfig.jsonfile
    # terminal running
    tsc --init
    Copy the code
    • Open thetsconfig.jsonFile to turn on the sourceMap option and specify the path to compiled output

    VS Code has built-in support for Ts debugging. To support debugging Ts in conjunction with executing Js Code, VS Code relies on the debugger’s Source Map to map Ts source to running Js, so the sourceMap option needs to be enabled.

    {
        "sourceMap": true."outDir": "./out"
    }
    Copy the code
    • Create a new index.ts file and write a basic TS code
    const num: number = 123;
    console.log(num);
    
    function fn(arg: string) :void {
      console.log('fn', arg);
    }
    
    fn("Hello");
    Copy the code
  • Manually compile and debug TS

    Among the basic TS items mentioned above:

    • The terminal executes the TS compilation commandtsc

    • You can see that the OUT folder has been generated, which contains oneindex.jsAnd aindex.js.mapfile

    • Add a breakpoint at will in index.ts

    • According to theF5orRun -> Start debuggingIn this case, you can see that normal debugging can be performed

  • Build debug TS with build tasks

    • According to theCtrl+Shift+BOr chooseTerminal -> Run the build task, a drop-down menu will pop up

    • chooseTSC build options, you can see that the compile file is automatically generated

    Note that if you are using a different terminal (such as CMder), this may not work. Use the default Powershell as shown below:

    • After you have the compiled file, pressF5Can be
  • Monitor changes and compile in real time

    • According to theCtrl + Shift + BSelect the monitor option to monitor changes in file content and recompile in real time

    • As shown below, it compiles in real time

How to create a Tasks configuration file

  • Method 1: ClickTerminal -> Configure Tasks -> Select TasksThe corresponding tasks.json configuration can be generated

  • Method 2: ClickTerminal -> Run the build task -> click the Settings iconYou can also generate the corresponding tasks.json configuration

Recompile every time you debug

  • The task.json configuration file has been generated as described above
{
	"version": "2.0.0"."tasks": [{"type": "typescript"."tsconfig": "tsconfig.json"."problemMatcher": [
        "$tsc"]."group": "build"."label": "TSC: build-tsconfig. json"}}]Copy the code
  • Click on theRun -> Add Configuration -> Select NodeJS

  • In the generatedlaunch.jsonFile, addpreLaunchTaskField, the value istasks.jsonthelabelValues must be the same, case sensitive. This field is used to perform changes before executing the commandtaskTask.

Note that you can specify the ts-compiled JS path through the outFiles field in the diagram if the compiled JS file is not in the corresponding location.

  • inindex.tsFile according to theF5When you start debugging, you can see that a build file has been generated before debugging, and then you can debug normally.

VsCode TS version description

  • Vscode itself has built-in support for ts

  • The built-in ts version (workspace version) of vscode is only used for IntelliSense (code hints), and the workspace ts version has nothing to do with the ts version used for compilation.

To modify the WORKSPACE TS version:

  • Select the typescript icon in the status bar and select Version Switch

  • Just choose the version you want

Debugging HTML projects

Now that we know how to debug ts, we can try debugging HTML files and introduce TS files into HTML files:

  • Create HTML and import TS compiled JS files
<! DOCTYPEhtml>
<html lang="en">
<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>
Copy the code
  • The ts source files are as follows:
const num: number =  1221;
console.log(num);

function fn(arg: string) :void {
  console.log('fn', arg);
}

document.body.append('World')

fn("he");
Copy the code
  • Play the debug

  • Launch. json Start command configuration
{
  // Use IntelliSense to learn about related attributes.
  // Hover to view descriptions of existing properties.
  / / for more information, please visit: 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: build-tsconfig. json"."webRoot": "${workspaceFolder}"}}]Copy the code
  • Select our startup command

  • According to theF5Chrome should be properly invoked, and vscode should debug the ts source

Two ways to debug a Vue project

Here are three ways to debug a VUe2 project in two ways, as well as in other frameworks:

Do not use vscode plugin Debugger method for chrome

  • Initialize the VUE project and configure itvue.config.js, specifying that the sourceMaps resource is to be generated
module.exports = {
  configureWebpack: {
    / / generated sourceMaps
    devtool: "source-map"}};Copy the code
  • Create it in the root directory. / vscode/launch. Json fileOr chooseRun -> Add Configuration -> 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"}}]Copy the code
  • Adding a Task Script
{
  "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}}}]Copy the code

The script is used to run the NPM run serve compile command.

  • According to theF5Start debugging

Note: The main point of this approach is that in the launch.json configuration file, the preLaunchTask field specifies that a task script should be run before debugging. The value of preLaunchTask corresponds to the label value in the tasks.json file.

For more details, you can click on the reference document here.

Debugger for Chrome with vscode

  • The first step is again to initialize the Vue project and addvue.config.jsFile configuration that specifies the sourceMaps resource to be generated
module.exports = {
  configureWebpack: {
    / / generated sourceMaps
    devtool: "source-map"}};Copy the code
  • Install the extension in vscodeDebugger for ChromePlug-ins, and make sure that plug-ins are not disabled

  • Start the project manually. No configuration is required for this methodtasks.jsontask
The terminal executes the command to start the project
npm run serve
Copy the code
  • According to theF5Start debugging

For more details, please refer to the reference document here.

Use the vscode plug-inDebugger for FirfoxDebug in Firefox

  • andDebugger for ChromeBasically the same. The difference is installationDebugger for FirfoxIn the launch.json configuration, add the debugging Firefox configuration as follows
{
  "version": "0.2.0"."configurations": [
    // Omit Chrome configuration...
    // Add the Firefox configuration below
    {
      "type": "firefox"."request": "launch"."reAttach": true."name": "vuejs: firefox"."url": "http://localhost:8080"."webRoot": "${workspaceFolder}/src"."pathMappings": [{ "url": "webpack:///src/"."path": "${webRoot}/"}}}]]Copy the code
  • Select the corresponding debugging command during debugging

Firefox does not trigger debugging when it is initially started and needs to be refreshed

Debug the Electron project

Electron is widely used for developing cross-platform system desktop applications. So let’s see how to debug the electron project created by vue-CLI-electric-Builder. The steps are as follows:

  • After initializing the project, modify it firstvue.config.jsFile configuration, add sourceMaps configuration:
module.exports = {
  configureWebpack: {
    devtool: 'source-map'}}Copy the code
  • Creating a debug configuration.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"]]}}Copy the code

Two debugging commands are configured: Electron: Main to debug the Main process and Electron: Renderer to debug the render process. Compounds []. Option is used to define compound debug options; Configurations define compound commands that are parallel; PreLaunchTask Is used to configure the task script that is executed before the command is executed. Its value corresponds to the label field in tasks.json. PreLaunchTask is used in Compounds to define the scripts that are executed before the Configurations composite task executes.

  • Creating a Task Script
{
  // 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\\."}}}]}Copy the code
  • Start debugging

You can debug the main process by setting a breakpoint on the main process-related code and launching the debug main process command

Note that the options parameter is added according to the actual situation, we need to run the project, for example, I here because the NPM command to start the project is:

"serve-local:dev": "cross-env VUE_APP_TYPE=local VUE_APP_ENV=dev vue-cli-service electron:serve"
Copy the code
  • The main process is successfully debugged

  • Start debugging the renderer process

Switch to the renderer debug option, set a breakpoint on the renderer code, and click Debug. Note that there is no breakpoint terminal and you need to manually refresh the software process with CTRL + R to see the breakpoint of the renderer process.

  • The effect after refreshing the render process, as shown below, has entered a breakpoint

  • Another way

Enable debugging of both the renderer and the main process, just switch to debug all options. Configurations of Compounds []. Configurations Note that because compounds[]. Configurations are executed in parallel in this way, there is no guarantee that the renderer debugging will be successfully attached to the main process. Sometimes the renderer debugging will fail. Therefore, you can take the above way to debug.

For more information on commissioning Electron, please click the Reference documentation.

Supplement: Go one step further

  • VS Debug React app documents
  • VS Debug the Next. Js document
  • More…

Other skills

Tip 1: Snippets

Install Snippets from the extension store

@category:"snippets"
Copy the code

Create a global snippet

  • chooseFile -> Preferences -> User fragments
  • chooseCreate a new global snippet file

  • Adding the file name of the snippet file generates a.code-snippets file

  • Defining user fragments

{
  "Autocomplete console.log": {
    "scope": "javascript,typescript"."prefix": "log"."body": [
        "console.log('$1');"."$2"]."description": "The console output. The log (")"}}Copy the code
keywords type instructions
scope string The scope in which the snippet works can be multiple languages, such asjavascript,typescriptThis parameter is valid in js and TSscopeField indicates that it is valid for all file types
prefix `string string[]`
body string[] Snippet content, each entry in the array will be one line
description string IntelliSenseAn optional description of the displayed fragment

1 1 –
n
Define the position of the cursor. The cursor jumps according to the number size by TAB. Pay attention to$0Is a special value that represents the cursor exit position and is the last cursor position.
  • Typing at the keyboardlogThe effect is as follows

  • Specify the default value at the cursor and check
"body": [ "console.log('${1:abc}');" ] .Copy the code

  • Specify multiple default values at the cursor and provide drop-down selection

With two vertical lines contains multiple choice value, directly use commas | | multiple choice value

"body": [
  "console.log('${1:abc}');",
  "${2|aaa,bbb,ccc|}"
],
Copy the code

Create a snippet of the current workspace

Just go to File -> Preferences -> User Snippets -> New snippets for the XXX folder, which will generate a.vscode/xxx.code-snippets file in the current workspace

Tip 2: Emmet

Vscode has built-in support for Emmet with no additional extension required. For example, Emmet for HTML is shown as follows:

Tip 3: Quickly rename code variables at the cursor

Select or at the cursor position and press F2 to rename all variables

Tip 4: Code refactoring advice

  • Select the code you want to refactor and click the icon of the yellow light that appears

  • Select the type of refactoring

  • Enter a new variable name

  • You can also refactor into functions

  • TS can also extract interfaces and so on

Added: VsCode extension plug-in development

What can the VsCode extension do?

  • Customize themes and file ICONS
  • Extended Workbench function
  • Create a webView
  • Custom new language prompts
  • Support for debugging specific runtime

Quick development of VsCode plug-in based on Yeoman:

  • The installationYeomanAnd plug-ins for generating templatesVS Code Extension Generator
The main node versions need to be 12 or higher, and node10 will cause an installation error
npm i -g yo generator-code
Copy the code
  • runyo codeCreate command to select the project template to build. Demonstrated hereNew extension

  • Follow the prompts to choose in turn

  • The generated content is as follows

  • According to theF5Builds the build project, at which point a new window automatically opens
  • Press in a new windowCtrl+Shfit+P, the inputHello WorldThe command

  • A popover effect will pop up

  • At this point, a simple plug-in is complete

conclusion

I am your old friend Leng Hammer. If you like the content above, please click “like” and collect it for further study. Reprint to indicate the author: Leng hammer.

Also recommended reading:

  • Awesome-canvas – Chinese version of Canvas resources, currently contains hundreds of fun and useful canvas library. Welcome to star ha ~ Github address github.com/chinaBerg/a…
  • Ts Masters: 22 examples that delve into the most esoteric of Ts’s advanced type tools Juejin. Cn/post / 699410…
  • Here are 28 Canvas libraries that will make you say wow Juejin. Cn/post / 703826…