Practical front-end code debugging skills

Table of contents

1. Using the browser's developer tools

1.1 Open the developer tools

1.2 Elements panel

Example: edit style

1.3 Console panel

Example: Debugging JavaScript Code

1.4 Sources panel

Example: Setting Breakpoints and Stepping Through Debugging

2. Use console.log to debug

Example: Use console.log to debug

Example: Output Objects and Arrays

3. Use the debugger statement to debug

Example: Use the debugger statement to debug

4. Debugging with Source Maps

Example: Debugging with Source Maps

5. Debugging with breakpoints

Example: Debugging with Breakpoints

6. Debugging with Chrome DevTools

Example: Debugging with Chrome DevTools

7. Debugging with VS Code

Example: Debugging with VS Code

8. Debugging with logging

Example: Debugging with Logging

9. Debugging with Assertions

Example: Debugging with Assertions

10. Debugging with debugging tools

10.1 React DevTools

10.2 Redux DevTools

10.3 Lighthouse

11. Summary


In the front-end development process, debugging is a very important link. Debugging helps us find bugs in our code, verify that functionality works correctly, and optimize the performance of our applications. However, since front-end code usually runs in the browser, debugging is not as intuitive and easy as it is on the back-end. Therefore, we need to master some practical front-end code debugging skills to improve debugging efficiency and accuracy. This blog will take you in-depth understanding of front-end code debugging techniques and tools, and demonstrate the use of each technique through actual code examples.

1. Using the browser's developer tools

Browser developer tools are one of the most commonly used tools for front-end debugging. Modern browsers have built-in developer tools that can help us check the HTML structure, CSS style and JavaScript code of a web page, and provide rich debugging functions.

1.1 Open the developer tools

In most modern browsers, you can F12open the developer tools by pressing the key or right-clicking on a web page and selecting "Inspect". In addition, you can also open it through the "Developer Tools" option in the menu bar.

1.2 Elements panel

The Elements panel is used to view and edit the HTML structure and CSS styles of web pages. You can view the corresponding HTML code and style by selecting an element in the Elements panel, and edit and preview the effect in real time.

Example: edit style

Let's demonstrate a simple example. Suppose we have an HTML page as follows:

<!DOCTYPE html>
<html>
<head>
  <title>样式调试示例</title>
  <link rel="stylesheet" href="styles.css">
</head>
<body>
  <h1>Hello, World!</h1>
</body>
</html>

Among them, styles.cssthe file contains a style definition:

 
 
h1 {
  color: red;
}

Open the page in a browser and open the Elements pane of the developer tools. Find <h1>Hello, World!</h1>the element and uncheck the checkbox to the right of the style, or directly modify the style value to color: blue. You will find that the color of the title will change to blue in real time, so as to verify whether the modified style takes effect.

1.3 Console panel

The Console panel is used to run JavaScript code in the browser and view output results. In the Console panel of the developer tools, you can enter any legal JavaScript code and press Entera key to execute the code. In addition, you can also console.log()output debugging information in the code through the method.

Example: Debugging JavaScript Code

Let's demonstrate a simple example. Suppose we have a JavaScript code as follows:

function add(a, b) {
  return a + b;
}

const result = add(1, 2);
console.log('Result:', result);

Copy the above code to the Console panel of the developer tool, and press Enterthe key. You will see the output in the Console panel Result: 3to verify that the code is running correctly.

1.4 Sources panel

The Sources panel is used to view and debug JavaScript code. In the Sources panel, you can view all JavaScript files loaded by the web page, and perform operations such as breakpoint setting, single-step debugging, and monitoring variables.

Example: Setting Breakpoints and Stepping Through Debugging

Let's demonstrate a simple example. Suppose we have a JavaScript code as follows:

<!DOCTYPE html>
<html>
<head>
  <title>调试示例</title>
</head>
<body>
  <h1>Hello, World!</h1>
  <script>
    function add(a, b) {
      return a + b;
    }

    const result = add(1, 2);
    console.log('Result:', result);
  </script>
</body>
</html>

Open this page in a browser, and open the Sources pane of the developer tools. Find <script>the code in the label, and click to set a breakpoint at the code line number on the left. Then, refresh the web page, and you will find that the page stops at the set breakpoint, so that you can step through the code and view the value of the variable.

2. Use console.log to debug

In front-end development, console.logit is one of the most commonly used debugging methods. By inserting statements into the code console.log, we can output information such as the value of the variable, the execution result of the function, etc., so as to better understand the execution process of the code.

Example: Use console.log to debug

Let's demonstrate a simple example. Suppose we have a JavaScript code as follows:

function add(a, b) {
  return a + b;
}

const result = add(1, 2);
console.log('Result:', result);

Open this page in a browser, and open the Console panel of the developer tools. You will see the output in the Console panel Result: 3to verify that the code is running correctly.

When used console.log, more complex information such as objects and arrays can also be output. In addition, we can use template strings to organize the output information.

Example: Output Objects and Arrays

 
 
const person = {
  name: 'John',
  age: 30,
  address: {
    city: 'New York',
    country: 'USA'
  }
};

const fruits = ['apple', 'banana', 'orange'];

console.log('Person:', person);
console.log(`Fruits: ${fruits.join(', ')}`);

3. Use the debugger statement to debug

In JavaScript, debuggera statement is a special statement that allows the browser to debuggerautomatically pause and enter debugging mode when the code executes to a statement. With debug mode, we can step through the code in the developer tools, view the value of variables, and perform single-step operations.

Example: Use the debugger statement to debug

Let's demonstrate a simple example. Suppose we have a JavaScript code as follows:

function add(a, b) {
  debugger;
  return a + b;
}

const result = add(1, 2);
console.log('Result:', result);

Open this page in a browser, and open the Sources pane of the developer tools. Refresh the page, and you will find that debugger;when the code executes to the statement, the page will automatically stop at the line, thus entering the debugging mode. In debug mode, you can step through the code and view the values ​​of variables.

4. Debugging with Source Maps

In front-end development, we usually compress and merge JavaScript code to reduce file size and network requests. However, the minified code is not intuitive when debugging because variable names and line numbers are modified. To solve this problem, we can use Source Maps to restore the compressed code for easier debugging.

Example: Debugging with Source Maps

First, we need to generate the Source Maps file. In most build tools, you can configure to generate Source Maps files.

 
 
{
  "name": "MyApp",
  "version": "1.0.0",
  "main": "dist/bundle.js",
  "scripts": {
    "build": "webpack --mode production --devtool source-map"
  },
  "devDependencies": {
    "webpack": "^5.50.0",
    "webpack-cli": "^4.8.0"
  }
}

In the above configuration, we added devtool: 'source-map'options to the Webpack configuration to generate Source Maps files.

Then, we need to introduce the Source Maps file in the HTML page.

 
 
<!DOCTYPE html>
<html>
<head>
  <title>调试示例</title>
</head>
<body>
  <h1>Hello, World!</h1>
  <script src="dist/bundle.js"></script>
</body>
</html>

You can now see the restored code in the Sources pane of the developer tools, making debugging easier.

5. Debugging with breakpoints

A breakpoint is a marker set in code to pause the execution of the code. debuggerIn the Sources panel of the developer tool, you can set a breakpoint by clicking on the line number of the code, or by inserting a statement in the code .

Example: Debugging with Breakpoints

Let's demonstrate a simple example. Suppose we have a JavaScript code as follows:

function add(a, b) {
  return a + b;
}

const result = add(1, 2);
console.log('Result:', result);

Open this page in a browser, and open the Sources pane of the developer tools. Find function add(a, b) { the line number where you are, and click the code line number to set a breakpoint. Refresh the page, and you will find that when the code execution reaches the breakpoint, the page will automatically stop at the line, thus entering the debugging mode. In debug mode, you can step through the code and view the values ​​of variables.

6. Debugging with Chrome DevTools

Chrome DevTools is a built-in developer tool of Google Chrome browser, which provides rich debugging functions, including Elements panel, Console panel, Sources panel, etc. In addition to the common debugging techniques mentioned above, Chrome DevTools also provides some advanced debugging functions, such as Performance panel, Memory panel, Network panel, etc.

Example: Debugging with Chrome DevTools

Let's demonstrate a simple example. Suppose we have a JavaScript code as follows:

 
 
<!DOCTYPE html>
<html>
<head>
  <title>调试示例</title>
</head>
<body>
  <h1>Hello, World!</h1>
  <script>
    function add(a, b) {
      return a + b;
    }

    const result = add(1, 2);
    console.log('Result:', result);
  </script>
</body>
</html>

Open the page in the Chrome browser and open the developer tools. You can Ctrl + Shift + Iopen the developer tools by pressing or right-clicking on a web page and selecting "Inspect". Then, refresh the page, and you will find that the page will automatically stop at the line of code const result = add(1, 2);, thus entering the debugging mode. In debug mode, you can step through the code and view the values ​​of variables.

7. Debugging with VS Code

In addition to browser developer tools, VS Code is another very popular front-end development tool that also provides powerful debugging functions. By setting breakpoints in VS Code, you can debug your code in the browser and view the values ​​of variables.

Example: Debugging with VS Code

First, we need to install the Chrome debugging plugin for VS Code. In VS Code, open the Extensions panel, search for the "Debugger for Chrome" plugin, and click the "Install" button to install it.

Next, we need to configure the debugging task in VS Code. .vscodeCreate a folder named under the root of your project , and create a launch.jsonfile named inside it, and configure it.

 
 
{
  "version": "0.2.0",
  "configurations": [
    {
      "type": "chrome",
      "request": "launch",
      "name": "Launch Chrome",
      "url": "http://localhost:8080",
      "webRoot": "${workspaceFolder}"
    }
  ]
}

In the above configuration, we specified the debugging task type as "chrome", and set the debugging URL and Web Root.

Then, we need to install the "Debugger for Chrome" plugin in the Chrome browser. Open the Extensions panel in the Chrome browser, search for the "Debugger for Chrome" plugin, and click the "Add to Chrome" button to install it.

Now, you can set breakpoints in VS Code, and click the "Run and Debug" button in the debug panel to start debugging. At this point, the Chrome browser will automatically open and enter the debugging mode. In debug mode, you can step through the code and view the values ​​of variables.

8. Debugging with logging

When debugging complex front-end applications, sometimes developer tools and breakpoint debugging alone are not enough. At this time, we can use logging to assist debugging. By inserting logging statements into the code, we can output more detailed information and thus gain a better understanding of the execution of the code.

Example: Debugging with Logging

Let's demonstrate a simple example. Suppose we have a JavaScript code as follows:

 
 
function add(a, b) {
  console.log('Adding', a, 'and', b);
  return a + b;
}

const result = add(1, 2);
console.log('Result:', result);

Open this page in a browser, and open the Console panel of the developer tools. You will see the output in the Console panel:

 
 
Adding 1 and 2
Result: 3

Through logging, we can clearly know the execution process of the code and view the value of the variable.

9. Debugging with Assertions

Assertions are a technique for verifying the results of code execution. By inserting assertion statements in the code, we can expect a certain condition to be true in the code, and throw an exception if the condition is not true, so as to quickly locate the problem.

Example: Debugging with Assertions

Let's demonstrate a simple example. Suppose we have a JavaScript code as follows:

 
 
function add(a, b) {
  console.assert(typeof a === 'number', 'a must be a number');
  console.assert(typeof b === 'number', 'b must be a number');
  return a + b;
}

const result = add(1, 2);
console.log('Result:', result);

Open this page in a browser, and open the Console panel of the developer tools. You will see the output in the Console panel:

 
 
Result: 3

Through assertion, we can ensure that the parameters of the function are legal, and throw an exception when the parameters are invalid, so as to quickly locate the problem.

10. Debugging with debugging tools

In addition to the developer tools of the browser and the debugging plug-in of VS Code, there are some tools dedicated to front-end debugging. These tools usually provide more powerful debugging functions, such as remote debugging, performance analysis and so on.

10.1 React DevTools

React DevTools is a debugging tool for the React framework, used to debug the state and behavior of React components. React DevTools can help us view the component hierarchy, props and state values, and update them in real time when the component state changes.

10.2 Redux DevTools

Redux DevTools is a debugging tool for the Redux library, used to debug the state and behavior of Redux. Redux DevTools can help us view the execution process of Redux's state tree, actions and reducers, and update them in real time when the state changes.

10.3 Lighthouse

Lighthouse is a performance analysis tool developed by Google to evaluate the performance and quality of web applications. Lighthouse can help us check the performance, accessibility, best practices and SEO of the application and provide suggestions for improvement.

11. Summary

This blog introduces some practical front-end code debugging techniques, including using browser developer tools, console.log, debugger statements, Source Maps, breakpoints, Chrome DevTools, VS Code, logging, assertion and debugging tools. By mastering these debugging skills, we can debug the front-end code more efficiently and improve development efficiency and quality.

Guess you like

Origin blog.csdn.net/m0_68036862/article/details/132040618
Recommended