概述
介绍 (Introduction)
Learning to debug is an essential skill for developers, as it allows them to efficiently fix errors during development. Knowing how to use debugging tools may not always be obvious when working with JavaScript outside of an integrated developer environment (IDE).
学习调试是开发人员的一项基本技能,因为它使他们能够在开发过程中有效地修复错误。 在集成开发人员环境 (IDE)之外使用JavaScript时,知道如何使用调试工具可能并不总是很明显。
This tutorial will take a look at debugging JavaScript with the Google Chrome DevTools, as well as with the popular text editor Visual Studio Code (VS Code).
本教程将介绍如何使用Google Chrome DevTools以及流行的文本编辑器Visual Studio Code (VS Code)调试JavaScript。
先决条件 (Prerequisites)
To complete this tutorial, you will need the following:
要完成本教程,您将需要以下内容:
The latest version of Google Chrome installed on your machine.
您的计算机上安装了最新版本的Google Chrome 。
The latest version of Visual Studio Code installed on your machine.
您的计算机上安装了最新版本的Visual Studio Code 。
Node.js installed locally, which you can do by following How to Install Node.js and Create a Local Development Environment.
Node.js在本地安装,您可以按照如何安装Node.js和创建本地开发环境进行操作 。
For this tutorial, you can apply the lessons to one of your own JavaScript projects that can be run on a Node server, but there is also the option to follow along using a sample application if you prefer.
对于本教程,您可以将课程应用于可以在节点服务器上运行的自己JavaScript项目之一,但是如果愿意,还可以选择使用示例应用程序。
第1步-创建示例应用程序(可选) (Step 1 — Creating a Sample App (Optional))
If you don’t have a JavaScript project to follow along with, you can complete this step to create a Quick Chat project.
如果没有后续JavaScript项目,则可以完成此步骤以创建快速聊天项目。
You use Git to clone the Design-and-Build-a-Chat-Application-with-Socket.io repo. Or you can download the zip file and unzip the contents.
您可以使用Git来克隆 Design-and-Build-a-Chat-Application-with-Socket.io存储库 。 或者,您可以下载压缩文件并解压缩内容。
Note: If you need Git installed on your system, consult Getting Started with Git.
注意:如果需要在系统上安装Git,请参阅《 Git入门》 。
For the purposes of this tutorial, you will use the code from Part 8. Take a moment to familiarize yourself with how you would expect the application to work.
出于本教程的目的,您将使用第8部分中的代码。 花一点时间熟悉一下应用程序的预期工作方式。
Start by navigating to the project directory and into the part-8
directory:
首先导航到项目目录并进入part-8
目录:
cd Design-and-Build-a-Chat-Application-with-Socket.io
cd使用socket.io设计和构建聊天应用程序
- cd part-8 CD第8部分
Next, install the npm packages for the project:
接下来,为项目安装npm软件包:
- npm install npm安装
Then, start the server:
然后,启动服务器:
- npm start npm开始
If you visit 127.0.0.1:3000
in Chrome, you should see a prompt for username. After providing a username and clicking the Chat! button, you will be directed to the chat app and see the following:
如果您在Chrome中访问127.0.0.1:3000
,则应该看到提示输入username的提示。 提供用户名并单击聊天之后! 按钮,您将被定向到聊天应用程序并看到以下内容:
User joined the chat...
用户加入了聊天...
By entering text in the input at the bottom of the window and clicking the Send button, your messages will display in the chat window.
通过在窗口底部的输入中输入文本并单击“ 发送”按钮,您的消息将显示在聊天窗口中。
If you open a new browser tab and visit the same URL, you can log in as another user and observe chat messages being sent to the chat windows in both browser tabs. This is the expected functionality for this application.
如果打开新的浏览器选项卡并访问相同的URL,则可以以其他用户身份登录,并在两个浏览器选项卡中观察到发送到聊天窗口的聊天消息。 这是此应用程序的预期功能。
错误介绍 (Introducing the Bug)
Now, you will intentionally introduce a tiny bug that fails to register who the user is after they’ve logged in.
现在,您将有意引入一个小错误,该错误无法在用户登录后注册用户。
Open part-8/public/app.js
in a text editor and find line 96
:
在文本编辑器中打开part-8/public/app.js
并找到line 96
:
//set the username and create logged in message
username = usernameInput.value;
Change this line to the following:
将此行更改为以下内容:
//set the username and create logged in message
username = usernameInput.text; // added bug
Refresh your browser tab. Login and observe the following:
刷新浏览器标签。 登录并观察以下内容:
- undefined joined the chat... 未定义加入聊天...
The app incorrectly grabs the user’s username by referencing usernameInput.text
instead of usernameInput.value
. We will use this to practice debugging.
该应用程序错误地通过引用usernameInput.text
而不是usernameInput.text
来获取用户的用户usernameInput.value
。 我们将使用它来练习调试。
第2步-了解调试基础 (Step 2 — Understanding the Basics of Debugging)
Before you begin to debug your app, it is helpful to be familiar with how debugging works. The idea of debugging is being able to (conditionally) trigger what are called breakpoints to pause the execution of your code. This provides you with the opportunity to look at the state of your application by taking an action such as inspecting variables. You can even take it a step further and ‘watch’ variables of your choosing, so that whenever your application is paused, you can inspect the values for these variables specifically.
在开始调试应用程序之前,熟悉调试的工作方式将很有帮助。 调试的想法是能够(有条件地)触发所谓的断点以暂停代码的执行。 这为您提供了通过执行诸如检查变量之类的操作来查看应用程序状态的机会。 您甚至可以更进一步,并“观察”您选择的变量,以便每当您的应用程序暂停时,您都可以专门检查这些变量的值。
After triggering a breakpoint, you will typically have the following options:
触发断点后,通常将具有以下选项:
- Continue the execution of your program. 继续执行程序。
- Step through your code line by line. 逐行浏览代码。
- Step out of the current function that you are in. 退出当前使用的功能。
- Step into the next function call. 进入下一个函数调用。
You’ll additionally have access to view the call stack. In other words, as functions call other functions in your program, you can inspect the history of those function calls.
您还将有权查看调用堆栈。 换句话说,当函数调用程序中的其他函数时,您可以检查这些函数调用的历史记录。
Now that you’ve covered the basics of how debugging works, you are ready to start debugging your app.
既然您已经了解了调试工作的基础知识,就可以开始调试应用程序了。
第3步-在Google Chrome浏览器中进行调试 (Step 3 — Debugging in Google Chrome)
To get started with debugging in Chrome, add a debugger
statement to your application.
要开始在Chrome中进行调试,请将debugger
语句添加到您的应用程序中。
If you are following along with the sample application, you can add it to the loginBtn
click event handler:
如果遵循示例应用程序,则可以将其添加到loginBtn
click事件处理程序中:
loginBtn.addEventListener('click', e => {
debugger; // added debugger
e.preventDefault();
if (!usernameInput.value) {
return console.log('Must supply a username');
}
//set the username and create logged in message
username = usernameInput.text; // added bug
sendMessage({ author: username, type: messageTypes.LOGIN });
//show chat window and hide login
loginWindow.classList.add('hidden');
chatWindow.classList.remove('hidden');
});
When this statement is reached, your application will be paused and the debug tools will automatically be activated. You will notice that the application will be grayed out to signify that it has been stopped. You will also see the Sources tab in Chrome DevTools has popped up:
达到此语句后,您的应用程序将被暂停,调试工具将被自动激活。 您会注意到该应用程序将变灰以表示它已被停止。 您还将看到Chrome DevTools中的Sources选项卡弹出:
Let’s breakdown what we’re seeing.
让我们细分我们所看到的。
资料来源 (Sources)
The first thing you might notice is what appears to be a copy of your code. This is the code that the browser has loaded and is running as your application. You can also see that the debugger
line is highlighted in a blue color to let you know that this is where your application has been paused:
您可能会注意到的第一件事似乎是代码的副本。 这是浏览器已加载并作为您的应用程序运行的代码。 您还可以看到debugger
行以蓝色突出显示,以告知您这是您的应用程序已暂停的地方:
Chrome gives you the ability to view this code for a reason. With the code in front of you, you can now set breakpoints. A breakpoint is an intentional stopping or pausing place in a program.
Chrome使您能够出于某种原因查看此代码。 现在有了代码,您就可以设置断点了 。 断点是程序中有意停止或暂停的地方。
To add a breakpoint, click in the gutter, or empty space, to the left of the line numbers. As you do, notice that Chrome now adds this breakpoint to the list of breakpoints further down.
要添加断点,请单击行号左侧的装订线或空白区域。 在执行操作时,请注意,Chrome现在将此断点添加到了更进一步的断点列表中。
范围 (Scope)
In the Scope tab, you have the ability to inspect variables in your application. You’ll notice there is a Local section (local scope to the function where the breakpoint is), a Global section (the global scope), and a Script section. In the Script section, you can view variables within the scope of the current script:
在“作用域”选项卡中,您可以检查应用程序中的变量。 您会注意到这里有一个Local节(断点所在的函数的本地作用域),一个Global节(全局作用域)和一个Script节。 在“ 脚本”部分中,您可以查看当前脚本范围内的变量:
This is where a significant amount of your debugging time will be spent. This is a much more efficient replacement for writing out many console.log()
statements.
这是您将花费大量调试时间的地方。 这是写出许多console.log()
语句的更有效的替代方法。
看 (Watch)
In addition to viewing variables in the Scope tab, you can also define variables that you want to look into specifically. By adding a variable to the Watch tab, each time you hit a breakpoint, you can quickly find the value of that variable (which may be undefined
depending on where you are in the code). Use the add icon (+) and enter the name of the variable you want to track.
除了在“ 作用域”选项卡中查看变量外,您还可以定义要专门查看的变量。 通过在“ 监视”选项卡中添加一个变量,每次您遇到断点时,您都可以快速找到该变量的值(根据您在代码中的位置,该变量的值可能是undefined
的)。 使用添加图标(+),然后输入要跟踪的变量的名称。
If you are following along with the sample application, you can use:
如果遵循示例应用程序,则可以使用:
usernameInput
步骤功能,调用堆栈和断点列表 (Step Functions, Call Stack, and Breakpoints List)
The last sections will allow you to view the list of breakpoints, call stack, etc.
最后几节将允许您查看断点列表,调用堆栈等。
If you are following along with the sample application, the call stack will contain the function listed for the event handler for the login button (loginBtn.addEventListener.e
). This function is listed because it is the only function that has been called so far. As functions call more functions, that chain will be updated appropriately.
如果您跟随示例应用程序一起使用,则调用堆栈将包含为登录按钮的事件处理程序列出的函数( loginBtn.addEventListener.e
)。 之所以列出此函数,是因为它是迄今为止唯一被调用的函数。 随着函数调用更多函数,该链将得到适当更新。
Notice also the arrow buttons at the top of the debugger.
还要注意调试器顶部的箭头按钮。
These correspond to the functions referenced for continuing execution of your code or stepping through it line by line or by function. Test these buttons a bit to get used to how you navigate the execution of your code.
这些与为继续执行代码或逐行或按功能单步执行代码所引用的功能相对应。 对这些按钮进行一些测试,以习惯于如何导航代码的执行。
Lastly, there are different kinds of breakpoints that can be set. Let’s take a look at creating a conditional breakpoint, one that will only get triggered if a certain condition is met. Right-click the gutter and choose Add conditional breakpoint….
最后,可以设置不同种类的断点。 让我们看一下创建一个条件断点,该条件断点只有在满足特定条件时才会被触发。 右键单击装订线,然后选择添加条件断点… 。
If you are following along with the sample application, you can create a breakpoint for when the the user attempts to log in without entering a username. Set a conditional breakpoint with the following condition:
如果您跟随示例应用程序一起使用,则可以为用户在不输入用户名的情况下尝试登录时创建一个断点。 使用以下条件设置条件断点:
usernameInput.text === ''
In the case of debugging the sample application, if you press the login button without entering a username, this breakpoint will be triggered. Otherwise code will continue to execute as normal.
在调试示例应用程序的情况下,如果在未输入用户名的情况下按下登录按钮,则会触发此断点。 否则,代码将继续正常执行。
Note that there are even more breakpoint options available that are not covered here.
请注意,这里没有涵盖更多可用的断点选项。
第4步-使用VS代码进行调试 (Step 4 — Debugging in VS Code)
As you’ve seen so far, the Chrome DevTools offer a great experience to debug your application with lots of functionality. However, Visual Studio Code in many ways has matching debugging functionality integrated more seamlessly into your environment.
正如您到目前为止所看到的,Chrome DevTools提供了使用许多功能来调试应用程序的丰富经验。 但是,Visual Studio Code在许多方面都将匹配的调试功能更无缝地集成到您的环境中。
To get started debugging in VS Code, install the Debugger for Chrome extension:
要开始使用VS Code进行调试,请安装Debugger for Chrome扩展程序 :
Let’s take a quick look at the debug tab in the sidebar (on the left side of your editor by default). Open the debug tab by clicking on the icon that looks like a bug:
让我们快速看一下侧边栏中的调试选项卡(默认情况下位于编辑器的左侧)。 通过单击看起来像是错误的图标来打开调试选项卡:
With this pane open, you will see similar tools to what we saw in Chrome: variables, watch, call stack, and breakpoints.
打开此窗格后,您将看到与Chrome中类似的工具:变量,监视,调用堆栈和断点。
The majority of the functionality that you get in Chrome DevTools is available right here inside of VS Code.
您可以在VS Code中使用Chrome DevTools中提供的大多数功能。
Now that you’ve seen the Debug tab, create a launch configuration that tells VS Code how to debug your application. VS Code stores debug configurations in a file called launch.json
inside of a folder named .vscode
.
现在您已经看到了Debug选项卡,创建一个启动配置,告诉VS Code如何调试您的应用程序。 VS Code将调试配置存储在名为launch.json
的文件夹内名为.vscode
的文件中。
To have VS Code create this file for you, you can click the link mentioned in the To customize Run and Debug create a launch.json file message in the pane. You could also accomplish this by navigating through the menu and selecting Run followed by Add Configuration…. Then you will choose Chrome.
要让VS Code为您创建此文件,可以单击窗格中“ 自定义运行并调试创建launch.json文件”消息中提到的链接。 您也可以通过在菜单中导航并选择Run(运行),然后选择Add Configuration ( 添加配置)来完成此操作 。 然后,您将选择Chrome 。
The specific configuration that you created will automatically attach to the application at the defined port.
您创建的特定配置将在定义的端口上自动附加到应用程序。
You may need to make changes to this configuration to correctly point to the source code for the app.
您可能需要对此配置进行更改,以正确指向该应用程序的源代码。
If you are following along with the sample application, you should change the port from 8080
to 3000
.
如果遵循示例应用程序,则应将端口从8080
更改为3000
。
The sample application is served from the public
directory and you should update webRoot
to reflect that.
该示例应用程序是从public
目录提供的,您应该更新webRoot
以反映该情况。
For debugging the sample application, the launch.json
file should resemble:
要调试示例应用程序, launch.json
文件应类似于:
{
"version": "0.2.0",
"configurations": [
{
"type": "chrome",
"request": "launch",
"name": "Launch Chrome",
"url": "http://localhost:3000",
"webRoot": "${workspaceFolder}/public"
}
]
}
Note: Keep in mind that your application must already be running locally at a certain port for this to work.
注意:请记住,您的应用程序必须已经在某个端口上本地运行才能正常工作。
With the configuration defined, you can now start your debug session by clicking the green play button at the top of the pane. You can also use the menu (Run and then Start Debugging) and keyboard shortcuts.
定义好配置后,您现在可以通过单击窗格顶部的绿色播放按钮来启动调试会话。 您还可以使用菜单(先运行 ,然后开始调试 )和键盘快捷键。
Your application will pop up in a Chrome window.
您的应用程序将在Chrome窗口中弹出。
You will notice the debug menu bar that popped up in the background inside of VS Code. With this debug toolbar, you can pause, restart, continue, and use step functions to navigate your code and interact with the debugger.
您会注意到VS Code内部背景中弹出的调试菜单栏。 使用此调试工具栏,您可以暂停,重新启动,继续,并使用步进功能来浏览代码并与调试器进行交互。
With debugging connected, you can set a breakpoint in the code like you did in Chrome. Click in the gutter next to the line number.
连接调试后,您可以像在Chrome中一样在代码中设置断点。 单击行号旁边的装订线。
If you are following along with the sample application, create a breakpoint in the same location as before, just inside the login event callback.
如果您跟随示例应用程序一起,请在登录事件回调内部,在与以前相同的位置创建一个断点。
Now, when trying to log in without entering a username, the breakpoint will trigger and switch the context back to VS Code for further investigation.
现在,当尝试在不输入用户名的情况下登录时,断点将触发并将上下文切换回VS Code进行进一步调查。
From here, the functionality that we discussed in Chrome maps over directly to VS Code. If you want to add a conditional breakpoint, right-click in the gutter and choose Add Conditional Breakpoint… with some condition. If you want to watch a variable, click to add a new one, and type the name of the variable to watch. If you want to explore variables, go to the Variables tab.
从这里开始,我们在Chrome中讨论的功能将直接映射到VS Code。 如果要添加条件断点,请在装订线中单击鼠标右键,然后选择“ 添加条件断点…” 。 如果要监视变量,请单击添加一个新变量,然后键入要监视的变量的名称。 如果要浏览变量,请转到“ 变量”选项卡。
结论 (Conclusion)
In this tutorial, you used both Chrome and Visual Studio Code to debug your application. Knowing how both of these options works will allow you to adopt a workflow that works best for you.
在本教程中,您同时使用了Chrome和Visual Studio Code来调试应用程序。 了解这两个选项的工作原理将使您能够采用最适合自己的工作流程。
Taking the next step as a developer involves taking advantage of the ecosystem of tools that are available to your programming language. Debugging is one of those topics that takes some time and effort to get started with, but ultimately the benefit will outweigh the cost.
作为开发人员采取下一步措施涉及利用您的编程语言可用的工具生态系统。 调试是入门中需要花费一些时间和精力的主题之一,但是最终的好处将超过成本。
翻译自: https://www.digitalocean.com/community/tutorials/how-to-debug-javascript-with-google-chrome-devtools-and-visual-studio-code
最后
以上就是明理银耳汤为你收集整理的如何使用Google Chrome DevTools和Visual Studio Code调试JavaScript的全部内容,希望文章能够帮你解决如何使用Google Chrome DevTools和Visual Studio Code调试JavaScript所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复